问题描述
我正在尝试使用Django中的uploadhandler上传文件.但是它返回了错误:
I'm trying to upload file using uploadhandler in Django. But it's returning the error:
代码:
def upload_form(request):
if request.method == 'POST':
outPath = '/opt/workspace/jup2/juppro/uploads/23232'
if not os.path.exists(outPath):
os.makedirs(outPath)
request.upload_handlers.insert(0, ProgressUploadHandler(request, outPath)) # place our custom upload in first position
upload_file = request.FILES.get('file', None) # start the upload
return HttpResponse("uploaded ok")
该代码有什么问题?
推荐答案
在开始上传之前,您必须定义uploadhandler.您可以访问request.POST的那一刻,文件已全部上传到内存或临时文件中.这使得定义上载处理程序毫无意义,因为上载已经完成.
You have to define the uploadhandler before you start uploading. The moment you can access request.POST the file has allready been uploaded to the memory or a temporary file. This makes defining an uploadhandler pointless, as the upload has allready been finished.
Django文档非常清楚何时定义自定义的上载处理程序:您只能在访问request.POST或request.FILES之前修改上载处理程序-在开始上载处理后更改上载处理程序没有任何意义."在不了解您的代码的情况下,我只能猜测,但是我认为将您的代码修改为以下内容就足够了:
Django docs are quite clear about when to define a custom uploadhandler: "You can only modify upload handlers before accessing request.POST or request.FILES -- it doesn't make sense to change upload handlers after upload handling has already started." Without knowing enough about your code i can only guess, but i think it should be enough to modify your code to the following:
def upload_form(request):
outPath = '/opt/workspace/jup2/juppro/uploads/23232'
if not os.path.exists(outPath):
os.makedirs(outPath)
request.upload_handlers.insert(0, ProgressUploadHandler(request, outPath)) # place our custom upload in first position
if request.method == 'POST':
upload_file = request.FILES.get('file', None) # start the upload
return HttpResponse("uploaded ok")
这篇关于尝试上传文件时“无法更改上传处理程序"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!