Flask 文件上传

File Upload in Flask

我正在尝试将文件从 Flask 传递到 MongoDB。该文件似乎没有正确上传以将其放入我的数据库中。我认为将它插入数据库本身的功能也不能正常工作。我不确定出了什么问题,因为我确定它非常接近。

def put_file(file_name, room_number):
    db_conn = get_db()
    with open('uploads/'+file_name, "r") as f:
        gfs.put(f, room=room_number)
    gfs = gridfs.GridFS(db_conn)

@app.route('/upload',methods=['POST'])
def upload():
    #get the name of the uploaded file
    file=request.files['file']
    #print "requested files"
    space=request.form['space']
    # if the file exists make it secure
    if file and space: #if the file exists
        #make the file same, remove unssopurted chars
        filename=secure_filename(file.filename)
        #move the file to our uploads folder
        file.save(os.path.join(app.config['UPLOAD_FOLDER'],file.name))
        put_file(filename,space)
        # remove the file from disk as we don't need it anymore after database insert.
        os.unlink(os.path.join( app.config['UPLOAD_FOLDER'] , filename))
        # maybe redirect user to the uploaded_file route, which will show the uploaded file.
        return render_template('index.html')#, filename = filename ,space = space) ##take the file name
    else:
        return render_template('invalid.html')

您的 file.save() 调用中存在错误:

file.save(os.path.join(app.config['UPLOAD_FOLDER'],file.name)

那不行。

而不是file.name,使用变量filename代替:

file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename)