简体   繁体   English

通过JavaScript上传文件:服务器上的文件无效

[英]File upload via JavaScript: Invalid file on server

I'm trying to upload a binary file (a PDF to be specific) with this JS-Snippet: 我正在尝试使用此JS-Snippet上传二进制文件(特定于PDF):

function uploadFile() {
    var reader = new FileReader();
    var file = document.getElementById('uploadInput').files[0];
    console.log(file.size);
    var xhr = new XMLHttpRequest();

    xhr.open('POST', 'custom?id=upload');
    xhr.setRequestHeader("Content-Type", "application/pdf");
    xhr.overrideMimeType('application/pdf');
    reader.onload = function(evt) {
        xhr.send(evt.target.result);
    };
    reader.readAsBinaryString(file);
}

On the serverside (Java) I'm receiving the request and writing the file to disk. 在服务器端(Java)上,我收到请求并将文件写入磁盘。
But instead of the expected ~3MB I'm getting ~4MB, with the effect that I only have blank pages, when opening the PDF. 但是,在打开PDF时,我没有达到预期的~3MB而是大约4MB,因为我只有空白页。

The header of the incoming request also specifies a Content-Length of ~4MB, so I'm fairly certain, that it is something on the clientside, that is causing the trouble. 传入请求的标头也指定了大约4MB的内容长度,所以我很确定,它是客户端的东西,这导致了麻烦。
Sending plain text files is no problem at all, they arrive exactly as they are supposed to be. 发送纯文本文件完全没有问题,它们完全按照预期的方式到达。

Since writing JavaScript and working in the web is not in my daily field of work, it is very well possible that I did something fundamentelly wrong. 由于编写JavaScript和在网络中工作不在我的日常工作领域,因此很有可能我做了一些基本错误的事情。

I would suspect 2 things you can try out: 我怀疑你可以尝试两件事:

  • check the MIME type on both end of the process, if it gets mangled somehow you have your answer 检查进程两端的MIME类型,如果它以某种方式被破坏你有答案
  • Your upload gets wrapped into a XMLHttprequest - you might have to Base64 Encode/Decode manually to get rid of the native byte representation in the PDF 您的上传被包装到XMLHttprequest中 - 您可能需要手动Base64编码/解码以摆脱PDF中的本机字节表示

Hopefully this will help you, good luck! 希望这对你有所帮助,祝你好运!

I found the solution: encode the data explicitly with Base64 before sending them and decode them appropriately on the receiving end. 我找到了解决方案:在发送数据之前使用Base64显式编码数据,并在接收端对其进行适当的解码。

function uploadFile() {
    var reader = new FileReader();
    var file = document.getElementById('uploadInput').files[0];
    console.log(file.size);
    var xhr = new XMLHttpRequest();

    xhr.open('POST', 'custom?id=upload');
    xhr.setRequestHeader("Content-Type", "text/plain; charset=x-user-defined");
    xhr.overrideMimeType('text/plain; charset=x-user-defined');
    reader.onload = function(evt) {
        var encoded = window.btoa(evt.target.result);
        xhr.send(encoded);
    };
    reader.readAsBinaryString(file);
}

I'm writing this to let anyone, who got the same problem, know of my solution. 我写这篇文章是为了让任何遇到同样问题的人知道我的解决方案。

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

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