@RequestMapping(value="/downloadImg")
public void downloadImg(HttpServletResponse response,HttpServletRequest request) throws Exception{
BufferedInputStream dis = null;
BufferedOutputStream fos = null;
String urlString = request.getParameter("urlString");
String fileName = urlString.substring(urlString.lastIndexOf('/') + 1);
try {
URL url = new URL(urlString);
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));
dis = new BufferedInputStream(url.openStream());
fos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
fos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dis != null)
dis.close();
if (fos != null)
fos.close();
}
}java WEB项目通过url下载图片到本地
最新推荐文章于 2024-04-26 20:10:19 发布
本文介绍了一个简单的图片下载接口实现方式,通过HTTP请求获取指定URL的图片,并将其作为附件形式返回给客户端。文章详细展示了如何使用Java处理HTTP请求,设置响应头以支持不同浏览器的兼容性,并确保文件正确下载。
1427

被折叠的 条评论
为什么被折叠?



