因为业务需求,上传Word文件需要编辑,但如何使用Blob方式,在数据库里存文件,就会造成格式消失。所以修改思路:上传文件到服务器本地,保证数据存储的完整性。
前端
html
<el-upload class="upload-demo" :action="item.fileUploadUrl" :show-file-list="false" :limit="1" :multiple="false" :auto-upload="true" :accept="item.accept" :before-upload="beforeUpload"
:headers="item.uploadHeaders" :data="item.uploadData">上传
</el-upload></el-button>
javascript
fileActionList: [
{
width: 60,
name: "合同文件",
fileUploadUrl: "*************/importContract",
uploadData: {},
uploadHeaders: {},
accept: ".doc,.docx,.pdf",
},
],
beforeUpload(file, fileList) {
let promise = new Promise((resolve) => {
this.$nextTick(function () {
resolve(true);
});
});
this.$message.success("上传成功");
return promise;
},
// 文件上传操作
handleImport(row) {
this.fileActionList[0].uploadData = {
id: row.id,
};
this.fileActionList[0].uploadHeaders = {
Authorization: Cookie.get("*******"),
};
},
就是常规的传文件
后端
java
@ApiOperation("导入合同文件")
@PostMapping("importContract")
public Result importData(@RequestParam(value="file") MultipartFile file, @RequestParam(value="id") Long id) throws Exception {
return projectService.importData(file, id);
}
@Override
public Result importData(MultipartFile file, Long id) throws Exception {
//获取文件名
InputStream path = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
path = file.getInputStream();
fis = (FileInputStream) path;
File dir = new File("file/project");
if (!dir.exists()) {
dir.mkdirs();
}
String filePath = "file/project/" + id + "_" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
fos = new FileOutputStream(filePath);
int readlen = 0;
//字节数组,一次读取8个字节
byte[] buf = new byte[8];
while ((readlen = fis.read(buf)) != -1) {
fos.write(buf, 0, readlen);
}
Project project = projectRepo.getById(id);
project.setContactFile(filePath);
projectRepo.save(project);
} catch (IOException e) {
log.error("" + e);
} finally {
path.close();
fis.close();
fos.close();
}
return Result.success("上传成功");
}
这此采用的思路就是 把文件读取后,写入相对路径,考虑到文件业务误传,服务器源文件不删除,通过时间戳保证唯一性。存到服务器本地。