我目前正在努力将图片从“ http://localhost:8080/download”下载到我的Android,以便将其设置为图片。 我发现了一个类似的问题:Download image from 'download url' Android, 但这并不能解决我的问题。
我的代码:
//Webserver Download Function
@RequestMapping(value = "/download", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<Object> downloadFile() throws FileNotFoundException {
File img = new File("D:\\Apprenticeship\\Work\\Projekte\\apli\\__Abschlussprojekt\\visitor.png");
InputStreamResource resource = new InputStreamResource(new FileInputStream(img));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Disposition", String.format("attachment; filename=\"%s\"", img.getName()));
httpHeaders.add("Cache-Control", "no-cache, no-store, must-revalidate");
httpHeaders.add("Pragma", "no-cache");
httpHeaders.add("Expires", "0");
return ResponseEntity.ok().headers(httpHeaders).contentLength(img.length()).contentType(MediaType.parseMediaType("image/png")).body(resource);
}
我想念什么?
答案 0 :(得分:0)
请尝试以下代码。那就是通常在我的应用程序中实现文件下载的方式。
@RequestMapping(value = "/download", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody void downloadFile(HttpServletResponse response) throws IOException {
File img = new File("D:\\Apprenticeship\\Work\\Projekte\\apli\\__Abschlussprojekt\\visitor.png");
response.setContentType("image/png");
response.setHeader("Content-Length", String.valueOf(img.length()));
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", img.getName()));
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
try ( FileInputStream in = new FileInputStream(img)) {
FileCopyUtils.copy(in, response.getOutputStream());
}
}