Java后端 根据图片的 url 地址返回流给前端发请求下载

@RequestMapping(value = "/downPosterImg.get", method = RequestMethod.GET)
	public  JsonDTO getRequest(@RequestParam String imgUrl, HttpServletResponse response) {
		String filename = "PosterImg_" +new Date().getTime()+ ".png";
		String path =filename;
		InputStream inputStream = null;
		OutputStream out = null;
		File file = null;
		try {
			file = new File(path);
			URL url =new URL(imgUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
//			conn.setConnectTimeout(1000);//超时提示1秒=1000毫秒
			FileUtils.copyURLToFile(url, file);
//			inputStream =  conn.getInputStream();//获取输出流

			response.setContentType("png/jpg");
			response.setHeader("Content-Disposition", "attachment" + ";filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
			byte[] bytes = new byte[(int)file.length()];
			inputStream = new FileInputStream(file);
			out = response.getOutputStream();
			out.write(bytes, 0, inputStream.read(bytes));
		}catch (Exception e) {
			return JsonDTO.createInstance().setData("download  io error ! ").setStatus(JsonDTO.FAIL).setMsg("请求处理失败") ;
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (file != null && file.exists()) {
				file.delete();
			}
		}
		return JsonDTO.createInstance().setStatus(JsonDTO.SUCCESS).setMsg("请求处理成功");
	}

你可能感兴趣的:(Java,java)