springBoot+vue实现文件下载功能
springBoot+vue实现文件,图片浏览器下载功能前端请求export function down(id){return request({url:'/file/upload/down/'+id,method:'get',**responseType:'blob'**})}前端请求方法引入请求的方法...
·
springBoot+vue实现文件,图片浏览器下载功能
前端请求
export function down(id){
return request({
url:'/file/upload/down/'+id,
method:'get',
**responseType:'blob'**
})
}
前端请求方法
引入请求的方法
down(“文件ID”).then(response => {
let blob = new Blob([response], {
type: "application/vnd.ms-excel;charset=utf-8"
});
let fileName = "图片" + Date.parse(new Date()) + ".png";
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
var link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
//释放内存
window.URL.revokeObjectURL(link.href);
}
})
.catch(error => {
console.log(error);
});
后端处理方法
@GetMapping(value = "/down/{fileId}")
public void downloadImage(HttpServletRequest request,HttpServletResponse response,@PathVariable String fileId) throws Exception{
//通过文件Id进行文件的查询
BsFileUpload fileUpload = bsFileUploadService.selectFileById(fileId);
logger.debug("the imageName is : "+fileUpload.getFileUrl());
String fileUrl = fileUpload.getFileUrl();
if(fileUrl != null){
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileUpload.getFileName()));
//将文件转换成二进制文件
**FileUtils.writeBytes(fileUrl,response.getOutputStream());**
}
}
writeBytes工具类
public static void writeBytes(String filePath, OutputStream os) throws IOException
{
FileInputStream fis = null;
try
{
File file = new File(filePath);
if (!file.exists())
{
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0)
{
os.write(b, 0, length);
}
}
catch (IOException e)
{
throw e;
}
finally
{
if (os != null)
{
try
{
os.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (fis != null)
{
try
{
fis.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)