使用FormData发送文件

时间:2018-07-11 09:33:25

标签: javascript python ajax flask

我正在尝试向Web应用程序中添加新功能,以使文件上传变得可用。

技术:Flask,Python3。我正在使用ajax对象FormData,但是它不起作用。 无法将文件发送到服务器。

javascript中的函数ajax()导致错误400。我试图在html中添加表单并使用FormData(form)。但这没有任何改变。

html

<label for="new-homework" class="add">Add</label>
    <button class="send">Submit</button>
    <input type="file" style="visibility:hidden;" multiple id="new-homework" value="Choose files">

javascript

function ajax(type, url, data, callback) { 
    var f = callback || function (data) {};
    var request = new XMLHttpRequest();
    request.onreadystatecheng = function () {
        if(request.readyState == 4 && request.status == 200){
            console.log('Success');
        }
    }
    request.open(type, url);
    if(type == 'POST')
        request.setRequestHeader('Content-type','application/json; charset=utf-8');
    console.log(data);
    request.send(data);    // Issue is here
}

var nf_button = document.getElementById("new-homework");
nf_button.addEventListener("change", function() {
    console.log('working');
    var files = nf_button.files;
    canSendFiles(files);
}, false);

function canSendFiles(files) {
    document.querySelector('button.send').onclick = function () {
        var form = new FormData();
        form.append('homework', files);
        console.log(form.getAll('homework'));
        ajax('POST', '/upload_file', form, function () {
            console.log('Sent');    
        });
    }
}

python

 UPLOAD_FOLDER = "C:\chess_school\pa\saved"
    ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif',
                              'TXT', 'PDF', 'PNG', 'JPG', 'JPEG', 'GIF']
                             )


    @app.route('/upload_file', methods=['GET', 'POST'])
    def upload_file():
        """
        Files upload

        :return:

        """
        if request.method == 'POST':
            file = request.files['file']
            print(file)
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                path = app.config['UPLOAD_FOLDER']
                if not os.path.exists(path):
                    os.makedirs(path)
                file.save(os.path.join(path, filename))
                return redirect(url_for('uploaded_file',
                                        filename=filename))
        return '''
        <!doctype html>
        <title>Upload new File</title>
        <h1>Upload new File</h1>
        <form action="" method=post enctype=multipart/form-data>
          <p><input type=file name=file>
             <input type=submit value=Upload>
        </form>
        '''


    @app.route('/uploads/<filename>')
    def uploaded_file(filename):
        return send_from_directory(app.config['UPLOAD_FOLDER'],
                                   filename)

怎么了?如何解决?

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我也不太确定,因为我也是新手,但是我觉得您在HTML中缺少名称

HTML

<input type="file" style="visibility:hidden;" multiple id="new-homework" value="Choose files" name="file">

Python

if request.method == 'POST':
            file = request.files['file']
            print(file)

谢谢。