springboot vue 下载文件 没有文件就下载的是空文件
前端 vue
// 下载文件
download(ref) { //
console.log(ref.id)
const id = ref.id
getBackupDown(id).then((res) => {
if (res.data === null) {
this.$message.error('下载失败')
} else {
this.$message.success('下载成功')
const blob = new Blob([res.data], {type: 'application;charset=utf-8'})
let link = document.createElement('a')
let href = window.URL.createObjectURL(blob)//下载链接
link.href = href
link.text = '下载'
link.download = ref.time + '.tar.gz'
document.body.appendChild(link)
link.click() //点击下载
document.body.removeChild(link)//下载完成移除元素
window.URL.revokeObjectURL(href) //释放blob对象
}
}).catch(err => {
this.$message.error('文件已删除')
})
},
export function getBackupDown (id) {
return axios({
url: 'main/selectBackup/download/'+id,
method: 'get',
responseType: 'blob'
})
}
后端 boot controller
@GetMapping("/download/{id}")
public void downLoad(HttpServletResponse response, @PathVariable("id") int id) throws UnsupportedEncodingException {
Backup backup = backupService.getById(id);
response.setContentType("application/octet-stream");
UploadUtil.down(response,backup.getPath());
}
后端 service
@Slf4j
public class UploadUtil {
public static void down(HttpServletResponse res, String pathAddress) throws UnsupportedEncodingException {
File file=new File(pathAddress);
if (!file.exists()){
log.error("没有此文件");
return;
}
String fileName = file.getName();
res.setHeader("content-type", "application/octet-stream");
res.setContentType("application/octet-stream");
res.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"iso-8859-1"));
byte[] buff = new byte[1024];
FileInputStream bis = null;
ServletOutputStream os = null;
try {
os = res.getOutputStream();
bis = new FileInputStream(file);
int readTmp = 0;
while ((readTmp = bis.read(buff)) != -1) {
os.write(buff, 0, readTmp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("success");
}
}