我正在嘗試創建一個java REST服務,它將下載word文檔。文件下載但內容只是垃圾十六進制,而不是實際的Word文檔內容。我的示例代碼如下。我錯過了什麼?文件之後的&具有相同數量的字節。REST服務發送損壞的文件
@SuppressWarnings("resource")
@RequestMapping(value = "get/testdoc", method=RequestMethod.GET, produces="application/octet-stream)
public @ResponseBody ResponseEntity<byte[]> getTestDoc() throws Throwable{
File doc = new File("C:\\temp\\file.doc");
InputStream is = new FileInputStream(doc);
byte[] bytes = IOUtils.toByteArray(is);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition" , "Attachment; filename=file.doc");
responseHeaders.setContentLength(ProposalDoc.length());
return new ResponseEntity<byte[]>(bytes, responseHeaders, HttpStatus.OK);
}
你怎麼確定下載的文件是「垃圾十六進制」?你有沒有試圖用Word打開它?此外,指定您使用的是哪個版本的Spring會很有幫助。 – Pyranja
如果不指定八位位組流和內容長度,該怎麼辦? –
我用word打開了文件。使用Spring 3.1.1。這需要在下載之前進行Base64編碼嗎? –