将用户上传的文件,下载本地并且将文件路径存入数据库
前端
vue-office目前只支持xlsx文件预览,不支持xls文件。所以在上传的时候需要设置accept属性限制用户可以选择的文件类型。
<input type="file" name="fileToUpload" id="fileToUpload" accept=".doc,.docx,.xlsx,.png,.jpg,.pdf,.txt">
将用户上传的文件,下载本地
const fileInput = document.getElementById('fileToUpload');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
//文件下载本地
insertReport(formData).then(res => {
//文件下载本地的相对路径插入数据库
toUpdate(数据库表Id,文件下载本地的相对路径).then( r =>{
//插入数据库成功
}).catch(error => {
this.$message.error("失败!");
});})
//日报路径插入数据库
export function toUpdate(reportId,url){
const data={
reportId,
url
}
return request({
url: '/sysReport/toUpdate',
method: 'post',
data:data
})
}
//日报下载本地
export function insertReport(fileData) {
return request({
contentType:false,
headers: {
'Content-Type': 'multipart/form-data'
},
url: '/sysReport/insertReport',
method: 'post',
data: fileData
})
}
后端
@PostMapping("/insertReport")
public Result toInputImport(@RequestParam("file") MultipartFile getFile) throws IOException {
return Result.success(this.sysReportService.toInputImport(getFile));
}@PostMapping("/toUpdate")
public Result toUpdate(@RequestBody Map map){
return Result.success(this.sysReportService.toUpdate(map));
}
@Override
public String toInputImport(MultipartFile getFile) throws IOException {
//定义全局唯一命名
String unique = UUID.randomUUID().toString().replace("-","");
//文件名
String fileName = getFile.getOriginalFilename();
//获取当前项目的根目录
String rootPath = System.getProperty("user.dir");
//定义相对路径
String fileType = fileName.substring(fileName.lastIndexOf('.'));
String partPath=unique+fileType;
String relativePath="\\src\\main\\resources\\image\\toSaveReport\\"+ partPath;
//拼接完整路径
String fullPath=rootPath+relativePath;
File file=new File(fullPath);
if (!file.exists()){
file.createNewFile();
}else{
file.delete();
file.createNewFile();
}
getFile.transferTo(file);
String url= "/image/toSaveReport/" +partPath;
return url;
}@Override
public String toUpdate(Map map) {
Boolean aBoolean = this.sysReportMapper.toUpdate(Integer.parseInt(map.get("reportId").toString()), map.get("url").toString());
if (aBoolean)
return "文件路径插入数据库成功";
else
return "文件路径插入数据库失败";
}
需要注意的是yml和配置文件需要做相应配置
文件在线预览
前端
#docx文档预览组件
npm install @vue-office/docx vue-demi
#excel文档预览组件
npm install @vue-office/excel vue-demi
#pdf文档预览组件
npm install @vue-office/pdf vue-demi
如果是vue2.6版本或以下还需要额外安装 @vue/composition-api
npm install @vue/composition-api
//vue-office的使用 请百度查看vue-office简介
此外
<iframe :src="getUrl" frameborder="0" width="100%" height="500"></iframe>
也可以实现文件预览
例如:
<iframe :src="getUrl" v-if="getUrl.includes('.jpg') || getUrl.includes('.png')" frameborder="0" width="100%" height="500"></iframe> //预览照片
<iframe :src="getUrl" v-else-if="getUrl.includes('.txt')" frameborder="0" width="100%" height="500"></iframe> //预览txt文件
完结