简体   繁体   中英

Java rest WS to download docx

I´m developing a Springboot rest-based web app. One of the WS must return a .docx document. The code is:

@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);
}

but I´m facing this error:

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

I searched other questions but none of them gave me a solution, mainly because they use javax.ws.rs but I don't want to rely on it.

What I´m looking for is a solution to the error I get or an alternative to my code (not javax.ws.rs dependant).

Thanks in advance.

Try returning array of bytes. Simplifying your code:

@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 is from org.apache.commons.io.IOUtils . I have not tested, but I have a similar method that return an image. I hope this help you.

You can set the stream directly in response.

@RequestMapping(value = "/get-doc",method = RequestMethod.GET)
public void getDoc(HttpServletResponse response){
     InputStream inputStream = new FileInputStream(file);
     IOUtils.copy(inputStream, response.getOutputStream());
     ..
     response.flushBuffer();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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