0

我正在使用以下系统来处理 AJAX 上传:https ://github.com/ded/reqwest

虽然它适用于我迄今为止尝试过的所有事情 - 我现在需要进行文件上传(当输入更改时)。你怎么做?到目前为止,我有:

document.getElementById('upload-file').addEventListener("change", function(e){

    var formData = new FormData();
    var file = e.currentTarget.files[0];

    reqwest({
        url: '/cgi-bin/upload.cgi',
        type: 'json',
        method: 'post',
        headers: {
              'enctype': 'multipart/form-data'
            },
        data: { the_file: file },
        error: function (err) {
            alert("There was an error: " + err)
        },
        success: function (data) {

        }
    });


});

不幸的是,这只是发送:

the_file [对象+文件]

...文件没有附加数据。

4

2 回答 2

1

您需要使用FileReader API。

document.getElementById('upload-file').addEventListener("change", function(e){
    var formData = new FormData();
    var file = e.currentTarget.files[0];
    var reader = new FileReader();

    // The load event is fired each time the reading operation is successfully completed. 
    reader.onload = function(event) {
        var jsonData = JSON.parse(event.target.result);  // event.target.result is the file's data
        reqwest({
            url: '/cgi-bin/upload.cgi',
            type: 'json',
            method: 'post',
            headers: {
                  'enctype': 'multipart/form-data'
                },
            data: { the_file: file },
            error: function (err) {
                alert("There was an error: " + err)
            },
            success: function (data) {

            }
        });  
    }

    reader.readAsText(file);
});
于 2018-03-27T06:55:40.270 回答
0

我刚刚在这里找到了答案:

https://github.com/ded/reqwest/issues/135

事实证明你需要:

processData: false, // important

所以完整的代码:

reqwest({
    url: '/cgi-bin/upload.cgi',
    type: 'json',
    method: 'post',
    processData: false, // important
    headers: {
          'enctype': 'multipart/form-data'
        },
    data: fd,
    error: function (err) {
        alert("There was an error: " + err)
    },
    success: function (data) {

    }
});

它现在完美地发送文件:)

于 2018-03-27T07:05:03.693 回答