'Cannot alter upload handlers' while trying to upload file

和自甴很熟 提交于 2021-01-27 06:29:58

问题


I'm trying to upload file using uploadhandler in Django. But it's returning the error:

You cannot alter upload handlers after the upload has been processed

Code:

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")

What's wrong with that code?


回答1:


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 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")


来源:https://stackoverflow.com/questions/5258850/cannot-alter-upload-handlers-while-trying-to-upload-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!