通过XHR上传文件并将流写入文件

时间:2017-04-26 11:06:07

标签: java servlets xmlhttprequest apache-commons-fileupload word-addins

我通过我的javascript word addin向一个servlet发送一个单词2013 docx。但是在将流写入文件之后,pdf / word(类型压缩)文件已损坏且具有不同的大小。它有更多的字节然后在js输出中的slice.value.size告诉我(当我将文件保存到单词中的hdd时显示相同的大小)。使用FormData和Apache Fileupload具有相同的结果。任何帮助将不胜感激。

JS:

function sendDoc(){
    Office.context.document.getFileAsync("pdf",
        function (result) {
            if (result.status == Office.AsyncResultStatus.Succeeded) {
                var myFile = result.value;
                myFile.getSliceAsync(0, function (slice) {
                    if (slice.status == Office.AsyncResultStatus.Succeeded) {
                        showMessage("sending (" + slice.value.size + " bytes)");

                        var request = new XMLHttpRequest();
                        request.onreadystatechange = function () {
                            if (request.readyState == 4) {
                                myFile.closeAsync(function (r) {
                                    if (r.status == Office.AsyncResultStatus.Succeeded) {
                                        showMessage("sent");
                                    }else {
                                        showMessage("error");
                                    }
                                });
                            }
                        }
                        request.open("POST", "myserver");
                        request.send(slice.value.data);

                    }else {
                        showMessage(slice.status);
                    }
                });
            } else {
                showMessage(result.status);
            }
        });
}

的Servlet

public void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            InputStream in = request.getInputStream();
            FileOutputStream out = new FileOutputStream("c:/temp/test.pdf");
            IOUtils.copy(in, out);
            in.close();
            out.close();

        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

1 个答案:

答案 0 :(得分:0)

自己解决了。我不得不将unicode号转换为字符并编码BASE64:

var fileContent = new String();
var docdata = slice.value.data;
for (var j = 0; j < docdata.length; j++) {
  fileContent += String.fromCharCode(docdata[j]);
}
var data = btoa(fileContent);
request.send(data);