JAVA下载单个文件并且返回浏览器,不写入本地
@RestController
@RequestMapping("xxx")
public class DownLoadController {
/**
* 下载单个文件并且返回浏览器,不写入本地
* @return
*/
@RequestMapping("/multipleDownLoad")
public static void getFile(String url, String destFileName, HttpServletResponse httpServletResponse)
throws ClientProtocolException, IOException {
// 生成一个httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
try {
httpServletResponse.reset();
httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + destFileName + ".jpg");
httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
OutputStream out = httpServletResponse.getOutputStream();
int l = 0;
byte[] tmp = new byte[1024];
/* while ((l = in.read(tmp)) != -1) {
out.write(tmp,0,1);
// 注意这里如果用OutputStream.write(buff)的话,图片会失真,大家可以试试
}*/
while ((l = in.read(tmp)) > 0) {
out.write(tmp, 0, l);
}
out.flush();
out.close();
} finally {
// 关闭低层流。
in.close();
}
httpclient.close();
}
}