gpt4 book ai didi

django - 在 Django : when to use save() vs chunks() vs cleaned_data? 中处理图像上传表单

转载 作者:行者123 更新时间:2023-11-30 23:59:46 25 4
gpt4 key购买 nike

我已经使用以下代码成功上传了一张图片:

View .py

from django.conf.urls.defaults import *
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django import template
from django.template import RequestContext

from mysite.uploadr.forms import UploadFileForm

def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.handle_uploaded_file(request.FILES['file'])
return HttpResponse(template.Template('''
<html><head><title>Uploaded</title></head> <body>
<h1>Uploaded</h1>
</body></html>
'''
).render( template.Context({}))
)
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form}, context_instance=RequestContext(request))

表格.py
from django import forms
from settings import MEDIA_ROOT

class UploadFileForm(forms.Form):
title = forms.CharField(max_length = 50)
file = forms.FileField()

def handle_uploaded_file(self,file):
#print type(file), "file.name=",file.name
#print dir(file)
destination = open(MEDIA_ROOT + '/images/'+file.name, 'wb+')
for chunk in file.chunks():
destination.write(chunk)

我想更进一步,将图像与正在上传的用户相关联。我看过一些例子并且喜欢这篇文章中的技术: https://stackoverflow.com/questions/3348013/django-image-file-uploads.

我注意到他们的代码使用了save() 和cleaned_data。是否不需要像文档中的示例那样遍历块并写入目标文件夹?我必须使用cleaned_data吗?只是想找出上传文件的最有效方法,我已经看到了很多不同的方法。非常感谢您的帮助。

最佳答案

当文件大于 settings.FILE_UPLOAD_MAX_MEMORY_SIZE 时需要分块(django 1.2 中默认为 2.5M)

看看 django.core.files.storage.FileSystemStorage 类(class)。它的 save() 方法为您执行分块保存工作并执行正确的文件锁定。

storage = FileSystemStorage(
location = '/var/www/site/upfiles',
base_url = '/upfiles'
)


content = request.FILES['the_file']
name = storage.save(None, content) #you can use some suggested name instead of
#None. content.name will be used with None
url = storage.url(name) #<-- get url for the saved file

在旧版本的 django(例如 1.0)中,文件名的生成存在缺陷。它不断添加 _如果重复上传相同的文件,文件名和上传的文件名会越来越长。这似乎在 1.2 版中得到了修复。

关于django - 在 Django : when to use save() vs chunks() vs cleaned_data? 中处理图像上传表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3485857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com