Java REST WS下载docx

标签 java rest spring-boot docx

我正在开发一个基于 Springboot Rest 的 Web 应用程序。其中一个 WS 必须返回 .docx 文档。代码是:

@RequestMapping(value = "/get-doc",method = RequestMethod.GET, produces="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
public @ResponseBody HttpEntity<File> getDoc() {
    File file = userService.getDocx();
    HttpHeaders header = new HttpHeaders();
    header.set("Content-Disposition", "attachment; filename=DocxProject.docx");
    header.setContentLength(file.length());

    return new HttpEntity<File>(file,header);
}

但我遇到了这个错误:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

我搜索了其他问题,但没有一个给我解决方案,主要是因为他们使用 javax.ws.rs 但我不想依赖它。

我正在寻找的是我遇到的错误的解决方案或我的代码的替代方案(不依赖 javax.ws.rs)。

提前致谢。

最佳答案

尝试返回字节数组。简化您的代码:

@RequestMapping(value = "/get-doc",method = RequestMethod.GET, produces="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
public @ResponseBody byte[] getDoc() {
    File file = userService.getDocx();
    FileInputStream fis = new FileInputStream(file);
    byte[] doc = IOUtils.toByteArray(fis);
    return doc;
}

IOUtils 来自org.apache.commons.io.IOUtils。我没有测试过,但我有一个类似的方法来返回图像。我希望这对您有帮助。

关于Java REST WS下载docx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36620290/

相关文章:

java - “Using non reentrant iterator method: Array.iterator()” 错误消息是什么意思?

java - 获取用户的所有主题标签

java - Spring 启动 : How to read resource from classpath in unit test

spring-boot - 从 Grails 3 迁移到 Spring-Boot

Java - Hibernate 调用 MySql 存储过程 - 警告消息

java.lang.IllegalArgumentException : Cannot bind argument at index 0 because the index is out of range. 该语句有4个参数

java - 请求收到 MultipartFile 时出现 MultipartException 和 IOFileUploadException

rest - 如何在 CakePHP 3 中使用 RESTful API 作为 ORM?

ios - 从 Swift 函数中的异步调用返回数据

java - SpringBoot 从 2.4.X 升级到 2.6.X 后无法运行我的 jar