File is empty after saving flask uploads

前端 未结 2 884
花落未央
花落未央 2021-01-24 12:33

I\'ve been trying to upload a file using Flask and HTML forms. Now I can save an uploaded file but it shows up empty (0 bytes). After that I store the form entries in a database

相关标签:
2条回答
  • 2021-01-24 13:24

    We don't really know what the class photos is, nor what it's method save does, but that's where the error is probably occurring.

    Try this instead:

    request.files['photo'].save('test.jpg')
    
    0 讨论(0)
  • 2021-01-24 13:24

    I realized that flask has a habit of including one empty file upload with the exact same name and details as one of the file attachments(usually the first attachment) WHEN you use the 'multiple' attribute in your form.

    My workaround was to

    1. create a temporary random filename and save the file upload
    2. use os.stat(temp_filename).st_size to check if the file is empty
    3. if the file is empty, delete it with os.remove, otherwise, rename the file to your preferred [secure] filename

    an example...

    # ...
    
    def upload_file(req):
        if req.method != 'POST': return
    
        # file with 'multiple' attribute is 'uploads'
        files = req.files.getlist("uploads")
    
        # get other single file attachments
        if req.files:
            for f in req.files: files.append(req.files[f])
    
        for f in files:
    
            if not f.filename: continue
    
            tmp_fname = YOUR_TEMPORARY_FILENAME
            while os.path.isfile(tmp_fname):
                # you can never rule out the possibility of similar random 
                # names
                tmp_fname = NEW_TEMPORARY_FILENAME
    
            # TEMP_FPATH is he root temporary directory
            f.save(os.path.join(TEMP_FPATH, tmp_fname))
    
            # and here comes the trick
            if os.stat(os.path.join(TEMP_FPATH, tmp_fname)).st_size:
                os.system("mv \"{}\" \"{}\" > /dev/null 2> /dev/null".format(
                    os.path.join(TEMP_FPATH, tmp_fname),
                    os.path.join(ACTUAL_FILEPATH, f.filename))
                ))
            else:
                # cleanup
                os.remove(os.path.join(TEMP_FPATH, tmp_fname))
                pass
    
    @app.route("/upload", methods=["POST"])
    def upload():
        upload_files(request)
    
        return "files are uploaded!"
    
    # ...
    
    0 讨论(0)
提交回复
热议问题