使用Office.js API将Word文档(.docx)保存到后端服务器

时间:2015-06-23 19:46:51

标签: javascript java spring ms-office openxml

我在将byte数组(使用Office.js从Microsoft Office的任务窗格中获取)保存到Word文档文件(服务器端)时遇到了一些麻烦。这就是我正在做的事情:

  • 我使用此library
  • 获取Word文档的内容

的JavaScript

$('#push').click(function () {
  $.when(OffQuery.getContent({ sliceSize: 1000000 }, function (j, data, result, file, opt) {
    // ...nothing interesting here
  })).then(function (finalByteArray, file, opt) {
    // (1) this line is changed...see the answer
    var fileContent = Base64.encode(finalByteArray); //encode the byte array into base64 string.

    $.ajax({
      url: '/webcontext/api/v1/documents',
      // (2) missing setting (see the answer)
      data: fileContent,
      type: 'POST'
    }).then(function () {
      // updateStatus('Done sending contents into server...');
    });
  }).progress(function(j, chunkOfData, result, file, opt){
    // ...nothing interesting here
});
  • 然后在Spring控制器中我这样做:

Java / Spring

@RequestMapping(method = RequestMethod.POST) // As OOXML
public void create(@RequestBody String fileContent, HttpServletRequest request) throws Exception { // TODO
  LOGGER.debug("{} {}", request.getMethod(), request.getRequestURI());
  //LOGGER.debug("fileContent: {}", fileContent);
  try {
    val base64 = Base64.decodeBase64(fileContent); // From Apache Commons Codecs

    FileUtils.writeByteArrayToFile(new File("assets/tests/output/some_file.docx"), base64);
  } catch (IOException e) {
    LOGGER.error("Crash! Something went wrong here while trying to save that...this is why: ", e);
  }
}

...但文件按原样保存;基本上是将byte数组作为文本文档保存到文件中。

我错过了什么吗?你有线索吗?有人使用过Office.js,任务窗格等等吗?

提前致谢...

更新1

事实证明finalByteArray正在转换为Base64字符串(fileContent),但是当我尝试在Java中执行反向操作时不起作用...如果有人之前已经这样做了, 请告诉我。我试过了:

  1. Mozilla页面中的示例
  2. Unibabel
  3. base64-js
  4. ...在Java端(将Base64 String解码为byte数组):

    1. 默认Base64编码器/解码器
    2. Base64 Apache codec

2 个答案:

答案 0 :(得分:2)

实际上,我发现了错误。这是在客户端。 Office.js SDK 中包含一项功能,可以将byte阵列转换为Base64 string - 虽然我不确定是否&# 39;随附所有版本,我使用 Office.js SDK 1.1

所以我将转换更改为:

var fileContent = OSF.OUtil.encodeBase64(finalByteArray);

...在AJAX调用中我添加了contentType设置:

  $.ajax({
    //...
    contentType: 'application/octet-stream',
    // ...
    type: 'POST'
  }).finish(function () {
    // ...
  });

通过正确设置内容类型,我能够发布正确的内容"到服务器。

  

即使我没有设置正确的Base64转换也是如此   Content Type,Spring控制器中收到的数据是   与客户报告的不同(在这种情况下更大)   侧。

我希望将来可以帮助其他人。 Microsoft Web中的示例非常清楚,但出于某种原因,#34;环境之间始终存在不同的情况"。

答案 1 :(得分:1)

您的代码中没有明显的错误,除了(如评论)我不知道为什么要从代码中删除最后一个字符。

为什么不使用像Firebug这样的javascript调试器和Web服务器的远程Java调试器来检查处理过程中的每一步并控制各种变量的内容(Javascript fileContent,Java fileContent,Java base64)来查找错误蔓延的地方。