想法
记录一下自己做这种需求的时候遇到的一些坑及方案 备查
前端如通过a标签js下载"
<a href="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558084900036&di=ae072a03a93c4739b6bdf63a030eed48&imgtype=0&src=http%3A%2F%2Fpic.downcc.com%2Fupload%2F2015-1%2F201512094354.jpg" download="logo.png">下载图片</a>
这种通过a标签download有些浏览器不支持
有时候也会出现在项目中点击出这张图片
在我实际操作中能下载,但是下载下来的图片不能使用
JAVA代码
前端按钮
<a href="/download?fileId=图片地址" id="download" ><button type="button" class="btn btn-default" >另存为</button></a>
不加A标签会导致前端响应为一张图片而无法下载
后台代码
@RequestMapping(value = "/download")
@ResponseBody
public void download(HttpServletResponse response,String fileId) throws IOException {
BufferedInputStream dis = null;
BufferedOutputStream fos = null;
try {
System.err.println("fileid:"+fileId);
// path是指欲下载的文件的路径。 绝对路径
File file = new File(fileId);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 步骤1:创建 URL
URL url = new URL (fileId);
// 步骤2:为specificURL 获得用户名称和密码 将它们放入String并用冒号":"分开
// 步骤4:对字符串进行编码
// 步骤5: 通过 URL 创建 URLConnection
URLConnection uc = url.openConnection();
//步骤6:为URLConnection 设置“授权”要求属性
uc.setRequestProperty ("Authorization", "Basic " );
URL url2 = uc.getURL();
response.setContentType("image/jpeg");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setHeader("Content-Length", String.valueOf(uc.getContentLength()));
dis = new BufferedInputStream(url2.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 (IOException e) {
throw new IOException();
}finally {
if(fos != null){
fos.close();
}
if(dis != null){
dis.close();
}
}
}`