jQuery 通过 AJAX Post 将文件输入作为 FileReader 二进制数据发布

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11399484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:34:26  来源:igfitidea点击:

Posting File Input as FileReader Binary Data through AJAX Post

jqueryajaxrestfilereader

提问by Eric H.

I am trying to post an attachment uploaded to an HTML file input to a web page through a rest API. The API documentation states that the post is a straight binary content as the body of the HTTP request, not a form file upload.

我正在尝试通过 rest API 将上传到 HTML 文件的附件发布到网页中。API 文档指出,该帖子是作为 HTTP 请求正文的直接二进制内容,而不是表单文件上传。

My code is as follows:

我的代码如下:

$('#_testButton').bind('click', function () {
    var file = document.getElementById('_testFile').files[0]
    var reader = new FileReader();
    reader.onload = function () {
        $.ajax({
            url: '/attachmentURL',
            type: 'POST',
            data: reader.result
        })
    }
    reader.readAsBinaryString(file)
})

I need this to work for a number of different mimeTypes, so I didn't declare it in the code above. However, I have tried declaring contentType:'application/msword' for a .doc file and also tried processData:false and contentType:false.

我需要它为许多不同的 mimeTypes 工作,所以我没有在上面的代码中声明它。但是,我尝试为 .doc 文件声明 contentType:'application/msword' 并尝试过 processData:false 和 contentType:false。

The data is being posted where it should. However, when I open the file, I get a message that says mimeType:application/x-empty with an empty file OR a file with a bunch of binary characters. I've tried .doc files and a pdf files and the result is the same for both.

数据被张贴在它应该发布的地方。但是,当我打开文件时,我收到一条消息,上面写着 mimeType:application/x-empty with a empty file or a file with a一堆二进制字符。我试过 .doc 文件和 pdf 文件,两者的结果都是一样的。

Does anyone have a clue what I can change to make this work?

有没有人知道我可以改变什么来使这项工作?

回答by Esailija

Simply sending the filereference as data (with processData: false) did the job for me at least:

简单地将file参考作为数据(带有processData: false)发送至少对我来说完成了这项工作:

$('#_testButton').bind('click', function () {
    var file = document.getElementById('_testFile').files[0];

    $.ajax({
        url: "/attachmentURL",
        type: "POST",
        data: file,
        processData: false
    });
});

It is described here: https://developer.mozilla.org/en/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data#section_3

它在这里描述:https: //developer.mozilla.org/en/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data#section_3

Sending a string (even if that string represents binary data) will not work because the browser will forcibly turn it into unicode and encode as utf-8 as specifiedwhich will corrupt the binary data:

发送字符串(即使该字符串代表二进制数据)将不起作用,因为浏览器会强制将其转换为 unicode 并按照指定的方式编码为 utf-8,这会破坏二进制数据:

If data is a string Let encoding be UTF-8.

Let mime type be "text/plain;charset=UTF-8".

Let the request entity body be data converted to Unicode and encoded as UTF-8.

如果数据是一个字符串让编码为 UTF-8。

让 mime 类型为“text/plain;charset=UTF-8”。

让请求实体主体为数据转换为Unicode并编码为UTF-8。

Sending a filereference (blob) will do this:

发送file引用 ( blob) 将执行以下操作:

If data is a Blob If the object's type attribute is not the empty string let mime type be its value.

Let the request entity body be the raw data represented by data.

如果 data 是 Blob 如果对象的 type 属性不是空字符串,则让 mime type 为其值。

让请求实体主体为 data 表示的原始数据。

回答by masoud soroush

var file;

var 文件;

        $('#_testFile').on("change", function (e) {
            file = e.target.files[0];
        });
        $('#_testButton').click(function () {
            var serverUrl = '/attachmentURL';

            $.ajax({
                type: "POST",
                beforeSend: function (request) {
                    request.setRequestHeader("Content-Type", file.type);
                },
                url: serverUrl,
                data: file,
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log("File available at: ", data);
                },
                error: function (data) {
                    var obj = jQuery.parseJSON(data);
                    alert(obj.error);
                }
            });
        });