文件上传
1.需求
1.1 文件需要在fastDfs,和本地各存一份 ,并且返回本地路径点击保存时将路径存入数据库
1.2 文件下载时先从本地拉取,如果本地文件不存在,从fastDfs拉取
2.效果展示
3.前段代码
3.1.0 合同签订框-基本信息
<el-row>
<el-form-item label="附件上传:" prop="remark" size="mini" >
<el-upload
class="upload-demo"
ref="uploadFileId" //保存返回的路径时使用
:action="uploadFileUrl" //必选参数,上传的地址
:on-preview="handlePreview" //点击文件列表中已上传的文件时的钩子
:on-success="handleSuccess" //文件上传成功时的钩子
:on-remove="handleRemove" //文件列表移除文件时的钩子
:before-upload="beforeUpload" //上传文件之前的钩子
:multiple =false //是否支持多选文件
:limit="1"
accept=".pdf"
:file-list="fileList" //上传的文件列表
:auto-upload="autoUpload"> //是否在选取文件后立即进行上传
<el-button size="small" type="primary">点击上传</el-button>
<span>上传pdf文件,不超过20M</span>
</el-upload>
</el-form-item>
</el-row>
3.1.1 合同签订框-合同签订
<el-table-column prop="filePath" label="附件" align="center"
show-overflow-tooltip>
<template slot-scope="scope">
<span v-if=" scope.row.filePath != null && scope.row.filePath != '' " style="color:#FF5722;">
<el-link size="mini" @click="previewFile(scope.row.filePath)">预览<i class="el-icon-view el-icon--right"></i> {{scope.row.filePath.split("/")[2]}}</el-link>
</span>
</template>
</el-table-column>
3.2 JS中需要定义的参数
uploadFileUrl: contextPath + '/api/apitudeFile/uploadSingleFile',
fileList: [],
autoUpload:false,
3.3 methods方法
//附件上传成功后的方法
handleSuccess:function(response, file, fileList){
vm.ruleForm.filePath = response.toString();
},
//移除附件列表
handleRemove:function(file, fileList){
if(isNotNULL(vm.ruleForm.id)){
vm.ruleForm.filePath=null;
let param ={id:vm.ruleForm.id};
this.$resource(contextPath + '/api/hrpEmployeeContract/deleteFilePath').query(
param
).then(function (response) {
this.search();
this.$message.warning("文件移除成功");
}).catch(function (error) {
this.showMsgError(error.data.errMsg);
});
}
},
//点击附件的方法
handlePreview:function(file){
this.previewFile(file.url);
},
//预览文件
previewFile(filePath){
window.top.vueObject.openHelp(contextPath + '/api/hrpEmployeeContract/downloadFile?filePath=' + filePath,'劳动合同预览');
},
//文件上传前的校验
beforeUpload:function(file){
let name = file.name;
let size = file.size / 1024 / 1024;
debugger
if(!(name.indexOf("pdf")>0) && !(name.indexOf("PDF")>0)){
this.$message.warning("请选择pdf文件");
return false;
}
if(size > 20 ){
this.$message.warning("文件大小不要过20M");
return false;
}
},
4 后台代码
4.1 文件上传后台
4.1.0 Controller
@RequestMapping("/uploadSingleFile")
public ResponseEntity<Object> uploadSingleFile(@RequestParam("file") MultipartFile multipartFile,HttpServletRequest request ){
String path = request.getSession().getServletContext().getRealPath("/upload");
String filePath = mmsApitudeFileApi.uploadSingleFile(multipartFile,path);
return new ResponseEntity<Object>(filePath,HttpStatus.OK);
}
4.1.1 ServiceImp
@Override
public String uploadSingleFile(MultipartFile file, String realPath) {
try {
//保存时的文件名
String originalFileName = file.getOriginalFilename();
String type = StringUtils.substringAfterLast(originalFileName,".");
String dateName = System.currentTimeMillis() +"_"+ originalFileName;
//保存文件的绝对路径
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdirs();
}
String pathToDb = "/upload/" + dateName;
MmsApitudeFile mmsApitudeFile = new MmsApitudeFile();
mmsApitudeFile.generateId();
mmsApitudeFile.setFileStatus("1");
//fileType字段存储业务主键
mmsApitudeFile.setFileType("");
mmsApitudeFile.setFileText(file.getBytes());
mmsApitudeFile.setFileSize(new BigDecimal(file.getSize()));
mmsApitudeFile.setFileForm(type);
mmsApitudeFile.setFileName(dateName);
mmsApitudeFile.setFileUploadTime(new Date());
mmsApitudeFile.setFileUrl(pathToDb);
String filePath = realPath + File.separator + dateName;
File tempFile = new File(filePath);
file.transferTo(tempFile);
mmsApitudeFileDao.insert(mmsApitudeFile);
return pathToDb;
}catch (Exception e ){
throw new RuntimeException(e);
}
}
4.2 文件预览,下载
@RequestMapping(value = "/downloadFile", method = RequestMethod.GET,produces="application/pdf")
public ResponseEntity<Object> downloadFile(String filePath, HttpServletRequest request, HttpServletResponse response) {
Assert.notBlank("filePath", "文件路径不可为空");
String path = request.getSession().getServletContext().getRealPath("");
File file = new File(path + filePath);
if (!file.exists()) {
MmsApitudeFile mmsApitudeFile = new MmsApitudeFile();
mmsApitudeFile.setFileUrl(filePath);
List<MmsApitudeFile> pictureList = mmsApitudeFileApi.findList(mmsApitudeFile);
mmsApitudeFileService.downloadFileIfNotExists(pictureList, path);
}
try {
String name = StringUtils.substringAfterLast(filePath, "/");
HttpHeaders headers = new HttpHeaders();
response.addHeader("Content-Disposition", "inline;filename="+new String(name.getBytes(StandardCharsets.UTF_8),"iso8859-1"));
return new ResponseEntity<Object>(FileUtil.readBytes(new File(path + filePath)), headers, HttpStatus.OK);
} catch (Exception e) {
throw new RuntimeException(e);
}
}