繁体   English   中英

为什么 FileReader 上传的数据超过了文件的长度?

[英]Why is the uploaded data from FileReader more than the file's length?

我想使用FileReaderPOST文件发布到我的界面。 一切正常(因为没有错误),只是发送的数据似乎在某处被破坏了。 检查线路时,我可以看到POSTContent-Length为 11910 字节,而我上传的文件只有 8852 字节大。

这是 Javascript 代码:

function readfile() {
    // #excelFile is a simple <input type="file">
    var file = $("#excelFile")[0].files[0];

    var reader = new FileReader();
    reader.addEventListener("load", (event) => {
        restPutPost("post", "rest/mapping", reader.result, 
        function(data) {
            console.log(`File ${file.name} uploaded.`);
        }, 
        function(xhr, status, error) {
            console.log(`Upload failed: ${error}`);
        }, 
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    });

    reader.readAsBinaryString(file);
}

restPutPost是一个方便的 function 我写道:

function restPutPost(method, url, body, callback = null, errorcallback = null, contenttype = "application/json") {
    actualbody = body;
    if (contenttype == "application/json") {
        actualbody = body != null?JSON.stringify(body): null;
    }

    $.ajax({
        type: method,
        url: url,
        headers: {
            Accept: "application/json"
        },
        data: actualbody,
        contentType: contenttype,
        success: function (data) {
            if (callback != null) {
                callback(data);
            }
        },
        error: function (xhr, status, error) {
            if (errorcallback != null) {
                errorcallback(xhr, xhr.status, error);
            }
        }
    });
}

我在发送二进制数据时遇到了一些问题。 首先,jQuery XHR 不保证数据不受影响。 二、JSON不支持二进制数据。

因此,为了解决这个问题,我决定将二进制数据转换为 Base64,并将其放入 JSON object:

var obj = {}
obj["exceldata"] = btoa(reader.result);

restPutPost("post", "rest/mapping", obj);

这样,我的整个接口保持 JSON,我仍然可以发送二进制数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM