一.文件上传
前端:
<el-upload
ref="filepath"
:file-list="filepathfileList"
action="#"
:auto-upload="false"
:on-change="handleChange">
<el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
</el-upload>
/**
js
* @description: 当文件选取发生变化时
* @param {*} file
* @param {*} fileList
* @return {*}
*/
handleChange(file, fileList) {
if (file.type != '' || file.type != null || file.type != undefined) {
// 计算文件的大小
const isLt5M = file.size / 1024 / 1024 < 5 // 这里做文件大小限制
// 如果大于50M
if (!isLt5M) {
this.$showMessage('上传文件大小不能超过 5MB!')
return
}
}
this.filepathfileList = fileList
if (this.filepathfileList.length > 1) {
this.filepathfileList.shift()
}
this.uploadFileRequest(file)
},
/**
* @description: 文件上传
* @param {*} fileId
* @param {*} file
* @return {*}
*/
uploadFileRequest(file) {
const param = {
file: file.raw
}
uploadefile(param).then(res => {
const path = res.data
const arr = res.data.split('\\')
const fileinfo = arr[arr.length - 1].split('.')
const type = fileinfo[1]
if (type == 'doc') {
this.fields.filepath = path
this.fields.filename = arr[arr.length - 1]
this.fields.filetype = type
}
this.$message.success('文件上传成功')
}).catch(e => {
this.$message.error('文件上传失败')
})
},
api
export function uploadefile(data) {
const param = new FormData()
Object.keys(data).forEach(key => {
param.append(key, data[key])
})
return request({
url: 'hrmContract/uploadefile',
method: 'post',
data: param,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
}
后端接收
@PostMapping("/uploadefile")
@ApiOperation("上传文件")
public Result uploadefile(@RequestParam("file") MultipartFile file) {
String dirPath = FileUtil.getTmpDirPath();
String path = "";
try {
InputStream inputStream = file.getInputStream();
path = dirPath + "/" + IdUtil.simpleUUID() + file.getOriginalFilename();
File fromStream = FileUtil.writeFromStream(inputStream, path);
} catch (IOException e) {
throw new CrmException(SystemCodeEnum.SYSTEM_UPLOAD_FILE_ERROR);
}
return Result.ok(path);
}
二:文件下载
后端根据文件地址返回文件流
@PostMapping("/downloadfile")
@ApiOperation("下载文件")
public void downloadfile(HttpServletResponse response){
try {
String path = "文件地址";
File file = new File(path);
String downloadFileName = new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1");
InputStream fis;
fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
}catch (Exception e) {
e.printStackTrace();
}
}
前端接收后直接调用即可
downloadFileWithBuffer(data, name) {
var downloadElement = document.createElement('a')
var href = window.URL.createObjectURL(data) // 创建下载的链接
downloadElement.href = href
downloadElement.download = name // 下载后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 点击下载
document.body.removeChild(downloadElement) // 下载完成移除元素
window.URL.revokeObjectURL(href) // 释放掉blob对象
}