因为业务需求,上传Word文件需要编辑,但如果使用Blob方式,在数据库里存文件,就会造成格式消失。所以修改思路:上传文件到服务器本地,保证数据存储的完整性。
前端
<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>
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("*******"),
};
},
就是常规的传文件
后端
@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("上传成功");
}
这此采用的思路就是 把文件读取后,写入相对路径,考虑到文件业务误传,服务器源文件不删除,通过时间戳保证唯一性。存到服务器本地。文章来源:https://www.toymoban.com/news/detail-581523.html
可以看到,最后格式都保留了下来
文章来源地址https://www.toymoban.com/news/detail-581523.html
到了这里,关于Springboot + Vue 上传Word、PDF文档并保留内部格式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!