2017-08-06 86 views
0

我正在運行端口3000燒瓶服務器,端點:3000/upload接受POST請求。但是,文件上傳部分不起作用。python燒瓶文件上傳失敗默默

@app.route('/upload', methods=['POST']) 
def post_upload(): 
    print ("test") 
    if request.method == 'POST': 
     print ("test2") 
     zfile = request.files['file'] 
     if zfile: 
      print("test3") 
      filename = secure_filename(zfile.filename) 
      zfile.save(os.path.join(app.config['UPLOAD_FOLDER'],filename)) 
      return "success" 
     else: 
      print ("test4") 
      return "fail" 
    return 'blah' 

我發送具有形狀數據的POST key等於filevalue是PNG圖像。客戶得到的迴應是:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> 
<title>400 Bad Request</title> 
<h1>Bad Request</h1> 
<p>The browser (or proxy) sent a request that this server could not understand.</p> 

服務器上的打印輸出:

* Running on http://0.0.0.0:3000/ (Press CTRL+C to quit) 
test 
test2 
104.148.224.253 - - [05/Aug/2017 19:30:04] "POST /upload HTTP/1.1" 400 - 

爲什麼zfile = request.files['file']後默默地失敗?

回答

0

嘗試使用flask的推薦格式進行文件上傳以更好地進行錯誤檢查。我猜字典中不存在'文件',因此在檢查值時會出錯。 'file'應該替換爲文件輸入元素的名稱,因此如果您有< input type = file name = file2 >,那麼它應該是request.files ['file2']。

http://flask.pocoo.org/docs/0.12/patterns/fileuploads/

def allowed_file(filename): 
    return '.' in filename and \ 
      filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 

@app.route('/', methods=['GET', 'POST']) 
def upload_file(): 
    if request.method == 'POST': 
     # check if the post request has the file part 
     if 'file' not in request.files: 
      flash('No file part') 
      return redirect(request.url) 
     file = request.files['file'] 
     # if user does not select file, browser also 
     # submit a empty part without filename 
     if file.filename == '': 
      flash('No selected file') 
      return redirect(request.url) 
     if file and allowed_file(file.filename): 
      filename = secure_filename(file.filename) 
      file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 
      return redirect(url_for('uploaded_file', 
           filename=filename)) 
    return ''' 
    <!doctype html> 
    <title>Upload new File</title> 
    <h1>Upload new File</h1> 
    <form method=post enctype=multipart/form-data> 
     <p><input type=file name=file> 
     <input type=submit value=Upload> 
    </form> 
    ''' 
+0

我先試了一下。我得到一個輸出說'沒有文件部分'。我使用POSTMAN,其中'key' ='file'和'value'是一個PNG圖像。 – bee

0

原來我不得不從被搞砸了,結果前一個郵差要求留下一些頭。我刪除它們,它的工作。標頭是

Authorization:Basic ... 
Content-Type:application/x-www-form-urlencoded 

我猜Content-Type頭搞砸了形式編碼,但我不知道如何或爲何,因爲它靜靜地失敗。

0

從一篇文章有​​同樣的問題。你可以使用它作爲參考。我使用燒瓶休息API。 here

解析器應該是這樣的。

parser.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files' )