我想從我的web應用程序使用瀏覽器在Android手機上下載文件(在我的情況下,我使用彈簧mvc儘管在這,因爲我認爲這是一個常見的問題,而不是框架特定)。事情是,嘗試在Android設備的鉻或本地瀏覽器的文件下載永遠不會結束,總是出現在下載應用程序In progress
或queue
(取決於Android版本,我嘗試與4.1.1和5.1.1)。從Android的HTTPS在瀏覽器中下載文件
我試圖改變參與http-headers
Content-Type
,Content-Disposition
與內聯或附件,指定Content-Length
沒有運氣。
事情是,在Windows或Linux的桌面瀏覽器的文件下載正確的情況下。
我的一些嘗試:在@RequestMapping
@RequestMapping(value= {"/evidenciaDownload"},method = RequestMethod.GET)
public ResponseEntity<byte[]> getEvidencia(
@RequestParam(value = "paramsCoded", required = true) String paramsCoded) throws IOException {
String url = configPropsService.getEvidenciaUrlDownload() + URLEncoder.encode(paramsCoded,"UTF-8");
logger.info("[getEvidencia] Recuperem l'evidencia de : " + url);
// bytes are correct
byte[] evidencia = downloadFile(url);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Content-Type", "application/pdf");
//responseHeaders.set("Content-Disposition","attachment; filename=\"evidencia.pdf\";");
responseHeaders.set("Content-Disposition","inline; filename=evidencia.pdf");
responseHeaders.setContentLength(evidencia.length);
return new ResponseEntity<byte[]>(evidencia, responseHeaders,HttpStatus.CREATED);
}
直接使用org.springframework.web.bind.annotation.ResponseBody
返回文檔bytes[]
和produces = "application/pdf"
:
使用
org.springframework.http.ResponseEntity
@RequestMapping(value= {"/evidenciaDownload"},method = RequestMethod.GET, produces = "application/pdf") public @ResponseBody byte[] getEvidencia( @RequestParam(value = "paramsCoded", required = true) String paramsCoded) throws IOException { String url = configPropsService.getEvidenciaUrlDownload() + URLEncoder.encode(paramsCoded,"UTF-8"); logger.info("[getEvidencia] Recuperem l'evidencia de : " + url); return downloadFile(url); }
或寫在
javax.servlet.http.HttpServletResponse
OutputStream的文件,並指定標題:@RequestMapping(value= {"/documentDownload"},method = RequestMethod.GET) public void getDocument( @RequestParam(value = "paramsCoded", required = true) String paramsCoded, HttpServletResponse response) throws IOException { String url = configPropsService.getDocumentsNotficacioUrlDownload() + URLEncoder.encode(paramsCoded,"UTF-8"); logger.info("[getDocument] Recuperem el document de : " + url); // bytes are correct byte[] downloadFile = downloadFile(url); ServletOutputStream outputStream = response.getOutputStream(); int fileLength = IOUtils.copy(new ByteArrayInputStream(downloadFile), outputStream); response.setHeader("Content-Disposition","attachment;filename=\"evidencia.pdf\""); response.setContentLength(fileLength); response.setContentType("application/pdf"); outputStream.flush(); outputStream.close(); }
的事情是,我說3例在Windows/Linux上的桌面瀏覽器中運行良好,惟未對鉻和原生瀏覽器android設備。