标签:
最近,写一个上次文件的django。死活传不过去。
在大神的帮助下面,最终还是成。 不过也发现一个问题:
django 官网文档:https://docs.djangoproject.com/en/1.8/topics/http/file-uploads/
表单定义
class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField()
表单对象生成.
form = UploadFileForm(request.POST, request.FILES)
request.POST里面是除了request.FILES外其他的参数,这里比如title.
但是奇怪的是如果我UploadFileForm里面只有一个tile。这里写成form = UploadFileForm( request.FILES),就是会报错…………(悲催的我搞了好久没明白,第一个参数)
发现这个第一个参数是被用来判断布尔值的。难道是用来YY的?写成UploadFileForm( {},request.FILES)就没问题了。
顺便贴下保存方法:
def handle_upload_file(f):
"""save the file which is loaded """
print(‘in handle‘)
try:
path = UPLOADED_FILE_DIRS + time.strftime(‘/%Y/%m/%d/%H/%M/%S/‘)
print(path)
if not int(os.path.exists(path)):
os.makedirs(path)
path_file_name = path+f.name
print(path_file_name)
destination = open(path_file_name, "wb+")
for chuck in f.chunks():
destination.write(chuck)
destination.close()
except Exception as e:
print(e)
return path_file_name
html中设置enctype="multipart/form-data"
标签:
原文地址:http://my.oschina.net/u/2367514/blog/508489