1、SpringMvc静态资源访问
需要所有图片在同一文件夹下,通过文件名直接访问
spring.mvc.static-path-pattern=pic/**
spring.resources.static-locations=file:/opt/project/epin/images
2、ResponseEntity返回二进制流
后端:
//读取文件流
@Override
public ResponseEntity<byte[]> readFile(String filePath, String path) throws IOException {
InputStream fileInputStream = null;
byte[] bytes = null;
HttpHeaders headers = null;
try {
String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
File file = new File(filePath);
if(!filePath.endsWith(".zip")){
fileInputStream = new FileInputStream(file);
}else{
//若是压缩文件
// new ZipFile(zipFilePath,);
// java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file,Charset.forName("GBK"));
// fileInputStream = ZipToTreeUtil.getZipFileInputStree(zipFile,path);
// fileName = path.substring(path.lastIndexOf("/")+1);
return null;
}
headers = new HttpHeaders();
fileName = URLEncoder.encode(fileName, "GBK");
if(filePath.endsWith(".jpg")||filePath.endsWith(".jpeg")) headers.setContentType(MediaType.IMAGE_JPEG);
else if(filePath.endsWith(".png")) headers.setContentType(MediaType.IMAGE_PNG);
else if(filePath.endsWith(".gif")) headers.setContentType(MediaType.IMAGE_GIF);
else {
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add("Content-Disposition", "attachment;filename=\""+ fileName + "\"");
}
bytes = IOUtils.toByteArray(fileInputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fileInputStream!=null)
fileInputStream.close();
}
return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.OK);
}
前端
this.axios({
url,
method,
params,
responseType:"blob"
})
.then(response=>{
console.log(response);
this.img = window.URL.createObjectURL(response.data) ;
})
踩坑:
后端设置返回类型image/jpeg(gif/png),前端设置返回类型blob,
转换成URL:window.URL.createObjectURL(response.data),一定要是data