a 便签的 链接需要 指向的action 返回的是 流
@ApiOperation(value="图片下载",notes="")
@RequestMapping(value="downPhoto",method=RequestMethod.GET)
public void downPhoto(
@RequestParam(value = "tid") Long tid,
HttpServletRequest request,
HttpServletResponse response
) throws BusinessException{
Photo photo = photoService.findPhoto(tid).getObject();
photoService.updatePhotoDownNum(tid);
String url = fileUploadPath+photo.getUrl();
String ext = url.substring(url.lastIndexOf("."));
//获取文件名
Long filename = new Date().getTime();
//设置响应头和下载保存的文件名
response.setContentType("APPLICATION/OCTET-STREAM");
//如果图片名称是中文需要设置转码
//response.setHeader("content-disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename+ext + "\"");
try {
//打开指定文件的流信息
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = new FileInputStream(url);
byte[] buffer = new byte[1024];
int i = -1;
while ((i = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, i);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// js 代码
$("[name='downloadButton']").on("click",function(){
var tid = $(this).attr("tid");
var empId = $(this).attr("empId");
if(userId == '' || !userId){
alert("请先登录!");
window.location = basePath;
}
var url = basePath+"/m/photo/downPhoto?tid="+tid;
//console.log(url);
//这里 是先创建 <a>标签,在a标签里面需要有一个 便签,里面的标签相对随意,比如:span标签,
//因为如果 只有 a 会用浏览器打开 图片
//注意我们 点击事件 是在 内部的标签触发的,通过事件冒泡传递给了 a,这样就可以直接 下载文件了
var aa = $("<a href="+url+" id='forDownPhoto' ><p></p></a>");
$(this).parent().append(aa);
aa.find("p").trigger("click");//触发内部的标签点击事件
aa.remove();//移除a标签
})