使用ajax和flask上传不同扩展名的文件

我正在使用flask通过ajax上传文件,代码是:


app = Flask(name) 

app.config["TEMPLATES_AUTO_RELOAD"] = True 

CORS(app) 

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024


@app.route("/upload//<element_id>", methods=['GET', 'POST'])

def ws_product_upload(element_id):

    print("Starting....")

    if request.is_xhr:

        print("xhr request received")

    if request.method == 'POST':

        f = request.files['file']

        process_inmemory( element_id, file=f)

        print("file received by post")

        if request.is_xhr:

            print("xhr request received inside post")

            return json.dumps({'result': True})

        return json.dumps({'result': True})

    return 'file uploaded needs a post call'

当我发送图像时,一切正常,但使用简单的 txt 文件时,会失败。


我努力了:


app.config["UPLOADED_FILES_ALLOW"] = ['.txt']  # with [] and with out with . and without and nothin

app.config["UPLOADED_FILES_DENY"] = 'exe'


我想用几乎所有的 mime 类型和扩展来做到这一点


我正在使用nginx + Gunicorn(不知道是否相关)


女巫才是正确的做法


忽然笑
浏览 66回答 2
2回答

神不在的星期二

所以 - 这是一些猜测:-)“UPLOADED_FILES_ALLOW”和“UPLOADED_FILES_DENY”是两个使用的环境变量名称Flask-Uploads- 这就是为什么我问你是否使用它,但你没有。“UPLOAD_EXTENSIONS”是 Miguel Grinberg 的大型教程中使用的环境变量 我假设您遵循了 Miguel Grinberg 的教程,并且在您的(截至目前)隐藏process_inmemory函数中执行了与教程中类似的操作,例如像if file_ext not in current_app.config['UPLOAD_EXTENSIONS']:.这实际上是唯一合理的解释 - 直到你真正向我们展示你的完整代码。

子衿沉夜

问题不是上传,问题是 chrome 和 cors,我不明白为什么,但上传图像它可以工作。解决方案是在函数之前放置一个 cors 装饰器cross_origin,如下所示:from flask_cors import CORS, cross_originapp = Flask(__name__)CORS(app)@app.route("/upload//<element_id>", methods=['GET', 'POST'])@cross_origin(supports_credentials=True, origins=["https://blabla.com","http://blabla:4202"])def ws_product_upload(element_id):&nbsp; &nbsp; print("Starting....")&nbsp; &nbsp; if request.is_xhr:&nbsp; &nbsp; &nbsp; &nbsp; print("xhr request received")&nbsp; &nbsp; if request.method == 'POST':
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python