我正在使用 angular
上传文件,并尝试在 flask
中访问上传的文件。
这没问题并且工作正常。但是,当我添加更多请求参数时,我似乎无法在 flask
request
对象中找到它们。
例如,使用 ngFileUpload
( https://github.com/danialfarid/ng-file-upload ) 上传文件,我可以像这样指定更多元信息:
$scope.upload = function (file) {
Upload.upload({
url: '/api/upload',
data: {file: file, 'username': $scope.username}
})
};
其中 username
是额外的元信息。
这是 flask 代码(使用 Flask-Restful):
from flask import Flask, request, Response
from flask.ext.restful import Api, Resource
ALLOWED_EXTENSIONS = {'csv'}
def allowed_file(fn):
return '.' in fn and fn.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
api = Api(app)
class Upload(Resource):
def post():
file = request.files['file']
fn = file.filename
if file and allowed_file(fn):
try:
# code for saving file
return Response(status=200)
except:
return Response(status=500)
return Response(status=500)
api.add_resource(Upload, '/api/upload')
在 flask 中,我可以通过 request.files['file']
访问 file
,但是 username
信息/变量无处可去被发现。
这在 Flask 中是不可能的,我是不是遗漏了什么,或者这里发生了什么?
最佳答案
我实际上认为@ciacicode 询问您的 python 代码是正确的。
您可能遇到了 CORS违反 Angular 调用 Python。
- 添加导入
参见 Flask-CORS:http://flask-cors.corydolphin.com/en/latest/index.html
从 flask.ext.cors 导入 CORS
- 将 CORS 添加到您的应用
简单添加到您的代码中:
app = Flask(__name__)
cors = CORS(app)
api = Api(app)
添加 CORS
让您的代码示例为我运行。
关于python - 使用angular上传文件时Flask访问请求数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37132000/