1. 上传
1.1 前端
export function importFile (param) {
return axios.post('/importFile', param)
}
获取文件,用FormData包装,调用接口
const element = document.getElementById('fileToUpload')
const files = element.files
const formData = new FormData()
const file = element.files[0]
formData.append('file', file)
importFile(formData).then(res => {
// ...
})
1.2 后端
写入本地磁盘
public void importFile(@RequestParam("file") MultipartFile file) {
LocalDateTime now = LocalDateTime.now();
String uploadPath = new StringBuilder()
.append(now.getYear()).append(File.separator)
.append(now.getMonthValue()).append(File.separator)
.append(now.getDayOfMonth()).append(File.separator)
.append(now.getHour()).append(File.separator)
.append(now.getMinute()).append(File.separator)
.append( now.getSecond()).append(File.separator)
.toString();
File dictionary = new File(localUploadDir + uploadPath);
if (!dictionary.exists()){
dictionary.mkdirs();
}
String fileName = file.getOriginalFilename();
String des = localUploadDir + uploadPath + fileName;
try (
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(des));
InputStream inputStream = file.getInputStream();
) {
if (!file.isEmpty()) {
int len;
byte[] bytes = new byte[1024 * 1024];
while ((len = inputStream.read(bytes)) > 0){
bufferedOutputStream.write(bytes,0, len);
}
}
}catch (Exception e){
e.printStackTrace();
logger.error("文件 {} 写入异常", fileName);
}
}
2. 下载
2.1 前端
修改返回类型
export function downloadFile (id) {
return axios.get('/downloadFile?id=' + id,
{
responseType: 'arraybuffer'
}
)
}
通过Blob下载
downloadFile(id).then(res => {
this.getDownloadFileResult (res, fileName)
})
getDownloadFileResult (res, fileName) {
const blob = new Blob([res])
const downloadLink = document.createElement('a')
// 创建下载的链接
const href = window.URL.createObjectURL(blob)
downloadLink.href = href
downloadLink.download = fileName
document.body.appendChild(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink)
// 释放掉Blob对象
window.URL.revokeObjectURL(href)
}
2.2 后端
public ResponseEntity<byte[]> downloadFile(@RequestParam("id") Integer id) {
String filePath = localUploadDir + "2020\2\17\17\23\50\测试.xlsx";
String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
byte[] bytes = null;
try {
bytes = FileUtils.readFileToByteArray(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
logger.error("文件 {} 读取异常", fileName);
}
return new ResponseEntity<>(bytes ,headers, HttpStatus.CREATED);
}
参考:
使用axios上传文件、下载(导出)文件
vue axios get和post请求下载文件,后台springmvc完整代码