使用AJAX上传文件、处理并使用Flask将结果返回到Javascript

Use AJAX to upload a file, process, and return a result to Javascript using Flask

本文关键字:Flask 结果 返回 Javascript AJAX 文件 处理 使用      更新时间:2023-11-11

我已经学会了如何使用AJAX和Flask上传文件,这样页面就不会刷新,文件就会上传到指定目录中的服务器。在Python方法(upload())中,我想用一些正则表达式处理文件名,并向Javascript文件返回一个数组。即使我试图请求一个数组,我还会返回render_template(index.html)吗?

HTML(index.HTML)

<form id="upload-file" role="form" action="sendQuestions" method="post" enctype="multipart/form-data">
    <div class="modal-body">
        <label for="file"><b>Upload packet here</b></label>
        <input type="file" name="file">
        <p class="help-block">Upload a .pdf or .docx file you want to read.</p>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button id="upload-file-btn" type="button" class="btn btn-primary" data-dismiss="modal" value="Upload">Upload</button>
    </div>
</form>

Javascript

$(function() {
    $('#upload-file-btn').click(function() {
        var form_data = new FormData($('#upload-file')[0]);
        $.ajax({
            type: 'POST',
            url: '/uploadajax',
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            async: false,
            success: function(data) {
                console.log('Success!');
            },
        });
    });
});

Python(烧瓶)

@app.route('/uploadajax', methods=['POST'])
def upload():
    file = request.files['file']
    if file and allowed_file(file.filename):
         filename = secure_filename(file.filename)
         file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return render_template('index.html')

我正在考虑在$.AJAX{}部分之后的Javascript中添加这个AJAX调用,但我做对了吗?我不确定是否可以在一个Javascript函数中两次调用同一个Python方法,或者是否有更好的方法。

ajaxRequest = ajaxFunction()
    ajax.onreadystatechange = function() {
        if (ajaxRequest.readyState === 4) {
            if (ajaxRequest.status === 200) {
                alert(ajaxRequest.responseText) //I want the Python to put the array into this ajaxRequest.responseText variable, not sure how.
            }
            else
                alert('Error with the XML request.')
        }
    }
    ajaxRequest.open("GET", 'uploadajax', true);
    ajaxRequest.send(null);

有什么帮助吗?谢谢

你没有说出你想要实现的目标(隐藏一些div,滚动窗口…),这是一个主要问题。总结应该做的事情:
不返回

return render_template('index.html')

但是fe。如果你想通知用户上传状态,请像一样为这个调用设置状态

return Response('OK')

或者其他状态-NOTOK之类的。然后在js:中

    success: function(data) {
        console.log('Success!');
    },

操纵响应

if (data == 'OK') {
  alert ('YAY, FILE UPLOADED');
};