2016-04-14 54 views
1

我正在開發一個Springboot基於rest的web應用程序。其中一個WS必須返回一個.docx文檔。該代碼是:Java休息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); 
} 

但I'm面臨着這樣的錯誤:

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

我搜索其他的問題,但他們沒有給我一個解決方案,主要是因爲他們使用javax.ws.rs但我不想依賴它。

我在找的是解決我得到的錯誤或我的代碼的替代方案(不依賴於javax.ws.rs)。

在此先感謝。

+0

看起來像是過濾標頭內容類型。 –

回答

1

嘗試返回字節數組。簡化您的代碼:

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

IOUtilsorg.apache.commons.io.IOUtils。我沒有測試,但我有一個類似的方法,返回一個圖像。我希望這對你有所幫助。

+0

您向我指出瞭解決方案。我把mi「File」改成了「byte []」,並且像你說的那樣使用了IOUtils,但是我保留了HttpEntity並且現在它正在工作。謝謝!! –

0

您可以直接設置流作爲響應。

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