后端下载
import lombok.Data;
@Data
public class DownloadDto {
private String id;
private String path;
private String name;
private String parentId;
}
/**
* 文件下载
*
* @param request
* @param response
* @throws IOException
*/
@PostMapping("/download")
public void upload(HttpServletRequest request, HttpServletResponse response, @RequestBody DownloadDto files) {
ServletOutputStream out = null;
FileInputStream ips = null;
try {
//获取文件存放的路径
File file = new File(files.getPath());
if (!file.exists()) {
//如果文件不存在就跳出
return;
}
ips = new FileInputStream(file);
response.setContentType("multipart/form-data");
//为文件重新设置名字,采用数据库内存储的文件名称
response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(files.getName().getBytes("UTF-8"), "ISO8859-1") + "\"");
out = response.getOutputStream();
//读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = ips.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
ips.close();
} catch (IOException e) {
System.out.println("关闭流出现异常");
e.printStackTrace();
}
}
return;
}
前端请求
details(index,path,name){
axios.post(
url,//请求的url
{
path:path,
name:name
},
{
responseType:'blob'//服务器返回的数据类型
}
).then((res)=>{
//接收对象
const content = res.data
const blob = new Blob([content])//构造一个blob对象来处理数据
//对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
//IE10以上支持blob但是依然不支持download
if ('download' in document.createElement('a')) { //支持a标签download的浏览器
const link = document.createElement('a')//创建a标签
link.download = name//a标签添加属性
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()//执行下载
URL.revokeObjectURL(link.href) //释放url
document.body.removeChild(link)//释放标签
} else { //其他浏览器
navigator.msSaveBlob(blob, name)
}
}).catch((err)=>{
// console.log(err);
})
},