文件上传
@PostMapping(value = PATH + "upload")
public ResponseEntity<FileInfo> upload(MultipartFile file) {
String filename = file.getOriginalFilename();
String suffix = filename.split("\\.")[1];
String path = FileUtil.getFilesPath();
File files = new File(path);
if (!files.exists()) {
files.mkdir();
}
String uuidName = UUID.randomUUID().toString().replace("-", "");
try {
file.transferTo(new File(path, uuidName + "." + suffix));
} catch (IOException e) {
e.printStackTrace();
}
FileInfo fileInfo = new FileInfo();
fileInfo.setName(filename);
fileInfo.setUuid(uuidName + "." + suffix);
fileInfo.setSuffix(suffix);
fileInfo.setFilePath(path + "\\" + uuidName + "." + suffix);
return ResponseEntity.ok(fileInfo);
}
文件下载
@PostMapping(value = PATH + "download")
public ResponseEntity download(@RequestBody FileInfo fileInfo) {
String uuid = fileInfo.getUuid();
String path = FileUtil.getFilesPath();
File file = new File(path + "\\" + uuid);
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
byte[] buffer = bos.toByteArray();
return ResponseEntity.ok().body(buffer);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ResponseEntity.ok("下载失败!");
}
前端处理
下载
download(){
this.$axios({
method:"post",
url:"/download",
data:fileInfo,
responseType: 'blob'
}).then(result => {
const blob = new Blob([result])
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
downloadElement.href = href
downloadElement.download = fileInfo.name
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)
})
}
预览
view(){
this.$axios({
method:"post",
url:"/download",
data:fileInfo,
responseType: 'blob'
}).then(result => {
const binaryData = []
binaryData.push(result)
const url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
window.open(url)
})
}