Skip to content

Commit f1feff1

Browse files
Patrick SandifordPatrick Sandiford
Patrick Sandiford
authored and
Patrick Sandiford
committed
file upload is almost working
1 parent 486b43c commit f1feff1

File tree

5 files changed

+77
-72
lines changed

5 files changed

+77
-72
lines changed

project/urls.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,18 @@
44
from django.contrib.auth import views as auth_views
55

66
from welcome.views import index, health
7-
from swift_browser.views import container, containers, create_container, delete_container
7+
from swift_browser.views import container, containers, create_container, delete_container, upload
88

99
urlpatterns = [
1010
url(r'^$', containers, name='containers'),
1111
url(r'^accounts/login/$', auth_views.login, name='login'),
1212
url(r'^logout/$', auth_views.logout, {'next_page': '/accounts/login'}, name='logout'),
1313
url(r'^health$', health),
1414
url(r'^admin/', include(admin.site.urls)),
15-
url(r'^container/create/$', create_container, name='create_container'),
16-
url(r'^container/delete/$', delete_container, name='delete_container'),
17-
url(r'^container/view/$', container, name='container'),
15+
url(r'^create_container/$', create_container, name='create_container'),
16+
url(r'^delete_container/$', delete_container, name='delete_container'),
17+
url(r'^view_container/$', container, name='container'),
18+
url(r'^upload/$', upload, name='upload'),
1819
]
1920

2021
if settings.DEBUG:

swift_browser/forms.py

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -36,22 +36,6 @@ def validate(self, value):
3636
super().validate(value)
3737

3838

39-
class SubDirectoryField(forms.CharField):
40-
"""
41-
A Subdirectory field is an object name with '/' characters to delimit
42-
the path
43-
"""
44-
def __init__(self, *args, **kwargs):
45-
kwargs['max_length'] = 1024
46-
super().__init__(**kwargs)
47-
48-
def to_python(self, value):
49-
return super().to_python(value)
50-
51-
def validate(self, value):
52-
super().validate(value)
53-
54-
5539
class CreateContainerForm(forms.Form):
5640
""" Simple form for container creation """
5741
container = ContainerNameField(label='Container Name')
@@ -66,8 +50,3 @@ class UploadFileForm(forms.Form):
6650
object_name = ObjectNameField(label='Object Name')
6751
container = ContainerNameField(label='Container')
6852

69-
class ViewContainerForm(forms.Form):
70-
""" Form used to view the contents of a container """
71-
container = ContainerNameField(widget=forms.HiddenInput())
72-
subdir = SubDirectoryField(required=False, widget=forms.HiddenInput())
73-

swift_browser/templates/container.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
</button>
3535

3636
<ul class="dropdown-menu">
37-
<li>Upload</li>
37+
<li><a href="{% url 'upload' %}?container={{container}}&subdir={{upload_subdir}}">Upload</a></li>
3838
<li class="divider" />
3939
<li>Create Pseudofolder </li>
4040
</ul>
@@ -76,7 +76,7 @@
7676
<tbody>
7777
<tr>
7878
<th colspan="5" class="center">
79-
<strong><center>There are no objects in this container yet. Upload new objects by clicking the red button.<center></strong>
79+
<strong><center>There are no objects in this container yet. Upload new objects by clicking the plus button.<center></strong>
8080
</th>
8181
</tr>
8282
</tbody>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
{% extends "base.html" %}
2+
{% load bootstrap3 %}
3+
{% block content %}
4+
5+
<div class="container">
6+
7+
<ul class="breadcrumb">
8+
<li><a href="{% url 'containers' %}">Containers</a></li>
9+
<li>
10+
<a href="{% url 'container' %}?container={{container}}">{{container}}</a>
11+
</li>
12+
13+
{% for path_entry in path %}
14+
<li>
15+
<a href="{% url 'container' %}?container={{container}}&subdir={{path_entry.subdir}}">{{path_entry.path_element}}</a>
16+
</li>
17+
{% endfor %}
18+
19+
</ul>
20+
21+
<form method="POST" action="{% url 'upload' %}" enctype="multipart/form-data">
22+
{% csrf_token %}
23+
{% bootstrap_form form%}
24+
{% bootstrap_button 'Upload' icon='upload' button_type='submit' %}
25+
</form>
26+
27+
{% block jsadd %}
28+
<script type="text/javascript">
29+
$('input[id=id_file]').change(function() {
30+
var file_name = $(this)[0].files[0].name;
31+
var path = '{{subdir}}' + file_name;
32+
$('input[id=id_object_name]').val(path);
33+
});
34+
</script>
35+
{% endblock %}
36+
37+
{% endblock %}
38+

swift_browser/views.py

Lines changed: 32 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from swiftclient import client
99
import logging
1010

11-
from .forms import CreateContainerForm, UploadFileForm, ViewContainerForm
11+
from .forms import CreateContainerForm, UploadFileForm
1212

1313
logger = logging.getLogger(__name__)
1414

@@ -22,44 +22,6 @@ def replace_hyphens(olddict):
2222
newdict[key] = value
2323
return newdict
2424

25-
def prefix_list(prefix):
26-
prefixes = []
27-
28-
if prefix:
29-
elements = prefix.split('/')
30-
elements = filter(None, elements)
31-
prefix = ""
32-
for element in elements:
33-
prefix += element + '/'
34-
prefixes.append({'display_name': element, 'full_name': prefix})
35-
36-
return prefixes
37-
38-
def pseudofolder_object_list(objects, prefix):
39-
pseudofolders = []
40-
objs = []
41-
42-
duplist = []
43-
44-
for obj in objects:
45-
# Rackspace Cloudfiles uses application/directory
46-
# Cyberduck uses application/x-directory
47-
if obj.get('content_type', None) in ('application/directory',
48-
'application/x-directory'):
49-
obj['subdir'] = obj['name']
50-
51-
if 'subdir' in obj:
52-
# make sure that there is a single slash at the end
53-
# Cyberduck appends a slash to the name of a pseudofolder
54-
entry = obj['subdir'].strip('/') + '/'
55-
if entry != prefix and entry not in duplist:
56-
duplist.append(entry)
57-
pseudofolders.append((entry, obj['subdir']))
58-
else:
59-
objs.append(obj)
60-
61-
return (pseudofolders, objs)
62-
6325
@login_required
6426
def containers(request):
6527
if 'auth_token' not in request.session.keys():
@@ -162,6 +124,7 @@ def container(request, container=None):
162124
return render(request, "container.html", {
163125
'container': container,
164126
'subdirs': subdirs,
127+
'upload_subdir': subdir,
165128
'folder_objects': folder_objects,
166129
'account': account,
167130
'public': public,
@@ -221,21 +184,45 @@ def upload(request):
221184
auth_token = request.session['auth_token']
222185
storage_url = request.session['storage_url']
223186

187+
container = ''
188+
subdir = ''
189+
if 'container' in request.GET.keys():
190+
container = request.GET['container']
191+
if 'subdir' in request.GET.keys():
192+
subdir = request.GET['subdir']
193+
194+
path = list()
195+
if subdir:
196+
current_path = ''
197+
for path_element in subdir.split('/'):
198+
if path_element:
199+
current_path += "%s/" % (path_element)
200+
path.append({ 'subdir': current_path, 'path_element': path_element })
201+
224202
if request.method == 'POST':
225-
form = UploadFileForm(request.POST)
203+
form = UploadFileForm(request.POST, request.FILES)
226204
if form.is_valid():
227-
container = form.cleaned_data['container_name']
205+
container = form.cleaned_data['container']
206+
object_name = form.cleaned_data['object_name']
207+
upload_file = request.FILES['file']
208+
logger.info("File upload for /%s/%s" % (container, object_name))
228209
try:
229210
http_conn = (urlparse(storage_url),
230211
client.HTTPConnection(storage_url, insecure=settings.SWIFT_SSL_INSECURE))
231-
client.put_container(storage_url, auth_token, container, http_conn=http_conn)
232-
messages.add_message(request, messages.INFO, "Container created.")
212+
client.put_object(storage_url, auth_token,
213+
container, object_name, http_conn=http_conn)
214+
messages.add_message(request, messages.INFO, "File uploaded.")
233215
except client.ClientException:
234216
messages.add_message(request, messages.ERROR, "Access denied.")
235217

236218
return redirect(containers)
237219
else:
238-
form = CreateContainerForm()
220+
form = UploadFileForm(initial={'container': container, 'object_name': subdir})
239221

240-
return render(request, 'create_container.html', {'form': form})
222+
return render(request, 'upload_file.html', {
223+
'form': form,
224+
'path': path,
225+
'container': container,
226+
'subdir': subdir,
227+
})
241228

0 commit comments

Comments
 (0)