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

Save Word document (.docx) using Office.js API to back-end server

本文关键字:docx 保存 服务器 后端 文档 js Office API Word 使用      更新时间:2023-09-26

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

  • 我正在使用此库获取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);
  }
}

但文件正在按原样保存;基本上将CCD_ 2数组作为文本文档保存到文件中。

我是不是错过了什么?你有什么线索吗?有人使用过Office.js、任务窗格之类的东西吗?

提前感谢。。。

更新1

事实证明,finalByteArray正在被转换为Base64字符串(fileContent),但当我尝试在Java中进行反向操作时,它不起作用。。。如果有人以前做过,请告诉我。我试过:

  1. Mozilla页面中的示例
  2. Unibabel
  3. base64 js

在Java侧(将Base64 String解码为byte阵列):

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

实际上,我发现了错误。它是在客户端。Office.js SDK中包含一个函数,用于将byte数组转换为Base64 string——尽管我不确定它是否与所有版本一起提供,但我使用的是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控制器中接收到的数据为与客户端中报告的不同(在这种情况下更大)一边

我希望这能在未来帮助其他人。MicrosoftWeb中的例子非常清楚,但出于某种原因,"不同环境之间总是有不同的东西"。

您的代码中没有明显的错误,只是(如注释所示)我不知道为什么要从代码中删除最后一个字符。

为什么不使用Firebug这样的javascript调试器和Web服务器的远程Java调试器来检查处理过程中的每一步,并控制各种变量(javascript fileContent、Java fileContent、Javabase64)的内容,以找出错误的来源