在Django 1.3中,用户上传一个“hello world”应用程序所需的最少示例代码是什么?
当前回答
不确定这种方法是否有任何缺点,但更小,在views.py中:
entry = form.save()
# save uploaded file
if request.FILES['myfile']:
entry.myfile.save(request.FILES['myfile']._name, request.FILES['myfile'], True)
其他回答
你可以参考Fine Uploader中的服务器示例,它有django版本。 https://github.com/FineUploader/server-examples/tree/master/python/django-fine-uploader
它非常优雅,最重要的是,它提供了特色的js lib。Template不包含在服务器示例中,但是你可以在它的网站上找到demo。 精美上传:http://fineuploader.com/demos.html
django-fine-uploader
views.py
UploadView将post和delete请求分派给各自的处理程序。
class UploadView(View):
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(UploadView, self).dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
"""A POST request. Validate the form and then handle the upload
based ont the POSTed data. Does not handle extra parameters yet.
"""
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_upload(request.FILES['qqfile'], form.cleaned_data)
return make_response(content=json.dumps({ 'success': True }))
else:
return make_response(status=400,
content=json.dumps({
'success': False,
'error': '%s' % repr(form.errors)
}))
def delete(self, request, *args, **kwargs):
"""A DELETE request. If found, deletes a file with the corresponding
UUID from the server's filesystem.
"""
qquuid = kwargs.get('qquuid', '')
if qquuid:
try:
handle_deleted_file(qquuid)
return make_response(content=json.dumps({ 'success': True }))
except Exception, e:
return make_response(status=400,
content=json.dumps({
'success': False,
'error': '%s' % repr(e)
}))
return make_response(status=404,
content=json.dumps({
'success': False,
'error': 'File not present'
}))
forms.py
class UploadFileForm(forms.Form):
""" This form represents a basic request from Fine Uploader.
The required fields will **always** be sent, the other fields are optional
based on your setup.
Edit this if you want to add custom parameters in the body of the POST
request.
"""
qqfile = forms.FileField()
qquuid = forms.CharField()
qqfilename = forms.CharField()
qqpartindex = forms.IntegerField(required=False)
qqchunksize = forms.IntegerField(required=False)
qqpartbyteoffset = forms.IntegerField(required=False)
qqtotalfilesize = forms.IntegerField(required=False)
qqtotalparts = forms.IntegerField(required=False)
不确定这种方法是否有任何缺点,但更小,在views.py中:
entry = form.save()
# save uploaded file
if request.FILES['myfile']:
entry.myfile.save(request.FILES['myfile']._name, request.FILES['myfile'], True)
我也有类似的要求。网上的大多数例子都要求创建模型和表单,我不想使用。这是我的最终代码。
if request.method == 'POST':
file1 = request.FILES['file']
contentOfFile = file1.read()
if file1:
return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})
在HTML中我写了:
{% block content %}
<h1>File content</h1>
<form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
<input type="submit" value="Upload" />
</form>
{% endblock %}
下面是显示文件内容的HTML:
{% block content %}
<h3>File uploaded successfully</h3>
{{file.name}}
</br>content = {{contentOfFile}}
{% endblock %}
以亨利为例:
import tempfile
import shutil
FILE_UPLOAD_DIR = '/home/imran/uploads'
def handle_uploaded_file(source):
fd, filepath = tempfile.mkstemp(prefix=source.name, dir=FILE_UPLOAD_DIR)
with open(filepath, 'wb') as dest:
shutil.copyfileobj(source, dest)
return filepath
你可以在上传文件对象的视图中调用handle_uploaded_file函数。这将在文件系统中保存具有唯一名称的文件(以原始上传文件的文件名作为前缀),并返回所保存文件的完整路径。您可以将该路径保存在数据库中,稍后对该文件进行处理。
我必须说我发现django的文档令人困惑。 还有一个最简单的例子,为什么要提到表单? 我在views.py中工作的例子是:-
for key, file in request.FILES.items():
path = file.name
dest = open(path, 'w')
if file.multiple_chunks:
for c in file.chunks():
dest.write(c)
else:
dest.write(file.read())
dest.close()
html文件看起来像下面的代码,尽管这个例子只上传了一个文件,保存文件的代码处理许多:-
<form action="/upload_file/" method="post" enctype="multipart/form-data">{% csrf_token %}
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
这些示例不是我的代码,它们是从我找到的其他两个示例中选取的。 我是一个相对初学者django,所以很可能我错过了一些关键点。
推荐文章
- 如何在django应用程序中显示favicon ?
- 如何在Python中获得所有直接子目录
- 如何在Django中设置时区
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- 如何在Ruby中创建文件
- django导入错误-没有core.management模块
- __FILE__宏显示完整路径
- 如何从外部访问本地Django web服务器
- 在Django模型中存储电话号码的最佳方法是什么?
- 如何禁用django-rest-framework的管理风格的可浏览界面?
- 如何获取请求。Django-Rest-Framework序列化器中的用户?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 我应该在.gitignore文件中添加Django迁移文件吗?