【问题标题】:Nginx - WSGI - Flask - File upload is failingNginx - WSGI - Flask - 文件上传失败
【发布时间】:2021-12-07 14:17:25
【问题描述】:

我正在尝试将文件从我的网络应用程序上传到用作应用程序 API 的烧瓶服务器。 正如标题中提到的,我使用 Nginx 作为我的网络服务器并使用 WSGI 运行烧瓶应用程序。 这是 webapp (React) 中的代码:

const formData = new FormData()
files.forEach((file) => {
  formData.append("files", file)
})
console.log('files', files)
console.log('formData', formData)
axios.post('https://api.web.app/uploadfile', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
}).then(response => {
  console.log('response.data.imgUrls', response.data.imgUrls)
  if (DLOrSOW === 'sow') {
    setSOWImgUrls(response.data.imgUrls)
  } else {
    setDLImgUrls(response.data.imgUrls)
  }
  
})
}

这是 Flask 上的代码:

@app.route('/uploadfile', methods=['POST'])
# @token_required
def upload_file():

        print("Req is POST")
        # check if the post request has the file part
        if 'files' not in request.files:
            print("No file found")
            flash('No file')
            return redirect(request.url)
        files = request.files.getlist('files')
        print(" files ", files)

        filePaths = []
        for file in files:
            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))
                print("url_for('download_file', name=filename)", url_for('download_file', name=filename))
                filePaths.append(url_for('download_file', name=filename))
        return jsonify({'imgUrls':filePaths })

客户端(浏览器)在控制台中响应:

Request header field Authorization is not allowed by Access-Control-Allow-Headers.
[Error] XMLHttpRequest cannot load https://api.web.app/uploadfile due to access control checks.

在 Flask 日志的另一端,我可以看到这个请求:

Oct 20 18:31:49 API uwsgi[1709272]: [pid: 1709272|app: 0|req: 36/81] 111.11.11.1 () {50 vars in 805 bytes} [Wed Oct 20 18:31:49 2021] OPTIONS /uploadfile => generated 6 bytes in 6 msecs (HTTP/1.1 200) 3 headers in 110 bytes (1 switches on core 0)

只是想补充一点,其他一切都可以正常工作。我能够向 Flask 中的所有其他路径发布、获取、放置等请求。 我认为导致这种情况的部分是“new FormData()”的使用

【问题讨论】:

    标签: file nginx flask upload wsgi


    【解决方案1】:

    在这种情况下,对于我的情况,通过在 Flask 路径中添加“GET”参数来解决问题: @app.route('/uploadfile', methods=['GET, 'POST']) 显然方法的顺序也很重要

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 2016-08-02
      • 2017-11-06
      • 2019-12-27
      • 2013-06-09
      • 2012-03-18
      相关资源
      最近更新 更多