====表结构task_file====
========前端具体到业务表单==========
<el-form-item label="任务附件" prop="taskAttachment"><el-upload ref="upload" accept=".jpg, .png, .txt, .xlsx, .doc, .docx, .xls, .pdf, .zip, .rar":action="upload.url" multiple :http-request="HttpUploadFile" :headers="upload.headers":file-list="upload.fileList" :on-remove="handleRemove" :on-success="handleFileSuccess":on-change="changeFileList" :data="getfileData()" :auto-upload="false"><el-button slot="trigger" size="small" type="primary">选取文件</el-button></el-upload></el-form-item>
参数说明===============
data
upload: {
// 是否禁用上传
isUploading: false,
// 设置上传的请求头部
headers: { Authorization: "Bearer " + getToken() },
// 上传的地址
url: process.env.VUE_APP_BASE_API + "/system/taskFile/upload/task",
// 上传的文件列表
fileList: []
},
=============
:action="upload.url" 上传后端接口
==================
multiple 可多选
==================
:http-request="HttpUploadFile" 增加数据
HttpUploadFile(file) {
this.fileData.append('files', file.file); // append增加数据
},
===============
headers="upload.headers" 请求头
=============
:file-list="upload.fileList" 文件列表
=======================
:on-remove="handleRemove" 移除文件操作
handleRemove(file, fileList) {
this.upload.fileList = fileList
this.deleteFilePath.push(file.url)
},
=================
:on-success="handleFileSuccess" 上传成功的操作
//文件上传成功后的钩子函数
handleFileSuccess(response, file, fileList) {
this.upload.isUploading = false;
this.upload.fileList = []
this.$modal.msgSuccess(response.msg);
},
==================
:on-change="changeFileList" 列表长度改变的操作
//fileList长度改变时触发
changeFileList(file, fileList) {
this.upload.fileList = fileList
console.log(this.upload.fileList)
},
======================
:data="getfileData()" 加载数据
getfileData() {
//此处的form是表单中的其它绑定值
return this.form.taskAttachment
},
=======================
:auto-upload="false" 是否自动上传
========================
==修改提交上传文件==
this.submitUpload()
submitUpload() {
//创建FormData对象,用于携带数据传递到后端
this.fileData = new FormData()
this.$refs.upload.submit();
this.fileData.append("data", JSON.stringify(this.form));
this.fileData.append("headers", { Authorization: "Bearer " + getToken() });
this.fileData.append("withCredentials", false)
this.fileData.append("filename", "file");
var i = this.upload.fileList.length
console.log(i)
if (i !== 0) {
//此处执行调用发送请求
uploadFile(this.fileData).then((res) => {
if (res.code === 200) {
this.upload.isUploading = false;
this.upload.fileList = []
// this.$modal.msgSuccess(res.msg);
this.open = false;
this.getList();
}
})
} else {
this.open = false;
this.getList();
//如果没有文件要上传在此处写逻辑
}
},
====下载====
<el-table-column label="任务附件" align="center">
<template slot-scope="scope">
<el-link type="primary" style="margin-right:10px" v-for=" item in scope.row.taskFileVos " :key="item.fileId"
@click.prevent="downloadFile(item)">{{ item.oFileName }}</el-link>
</template>
</el-table-column>
=============
downloadFile(item) {
this.download('system/taskFile/download/resource', {
filePath: item.filePath,
}, item.oFileName)
},
===前端展现===
<el-table-column label="任务附件" align="center"><template slot-scope="scope"><el-link type="primary" style="margin-right:10px" v-for=" item in scope.row.taskFileVos " :key="item.fileId"@click.prevent="downloadFile(item)">{{ item.oFileName }}</el-link></template></el-table-column>
====后端====
构造回显表单构造集成实体类供查询使用
/*文件及文件附件*/ public class TaskVo extends SysProjectTask {private List<TaskFile> taskFileVos;public TaskVo(List<TaskFile> taskFileVos) {this.taskFileVos = taskFileVos;}public TaskVo() {}public List<TaskFile> getTaskFileVos() {return taskFileVos;}public void setTaskFileVos(List<TaskFile> taskFileVos) {this.taskFileVos = taskFileVos;}@Overridepublic String toString() {return "TaskVo{" +"taskFileVos=" + taskFileVos +'}';} }
==============
@RestController
@RequestMapping("/taskFile")
public class TaskFileController {@Autowiredprivate ITaskFileService taskFileService;/*任务附件上传*/@PostMapping("/upload/task")@Transactional(rollbackFor = Exception.class)public AjaxResult uploadFile(@RequestParam("files") MultipartFile[] files, @RequestParam("data") String data) {try {//这里的data是同时携带的其它信息就是前端的form里的信息,可以是用下面的json方式解析为自己相应的对象System.out.println(data);SysProjectTask sysProjectTask = JSONObject.toJavaObject(JSONObject.parseObject(data), SysProjectTask.class);// 上传文件路径 E:/ruoyi/uploadPathString filePath = RuoYiConfig.getUploadPath();System.out.println("========================"+filePath);String fileName = "";String url = "";// 上传并返回新文件名称AjaxResult ajax = AjaxResult.success();for (int i = 0; i < files.length; i++) {/*/profile/upload/2024/03/19/4004308e-fd63-4323-89cc-6a7c8641f148.txt*/
// fileName = FileUploadUtils.upload(filePath, files[i]);fileName = FileUploadUtils.upload(filePath, files[i]);url = filePath+fileName;TaskFile taskFile = new TaskFile();/*任务文件名,保存的名称*/taskFile.setTaskName(fileName);/*文件保存路径*/taskFile.setFilePath(url);/*文件原名*/taskFile.setoFileName(files[i].getOriginalFilename());/*关联任务ID*/taskFile.setTaskId(sysProjectTask.getTaskId());/*文件大小*/taskFile.setFileSize(String.valueOf(files[i].getSize()));/*w文件类型*/taskFile.setFileType(files[i].getContentType());taskFile.setUploadTime(DateUtils.getNowDate());taskFile.setProjectId(sysProjectTask.getProjectId());taskFileService.insertTaskFile(taskFile);}return ajax;} catch (Exception e) {System.out.println(e.getMessage());return AjaxResult.error(e.getMessage());}}/*通过任务ID去查询任务附件名称*/@GetMapping("/read/{taskId}")@Transactional(rollbackFor = Exception.class)public AjaxResult readTaskFile(@PathVariable("taskId") Long taskId) {TaskFile taskFile = new TaskFile();taskFile.setTaskId(taskId);List<TaskFile> taskFiles = taskFileService.selectTaskFileList(taskFile);System.out.println(taskFiles);List<TaskFileVo> taskFileVos = new ArrayList<>();taskFiles.forEach(taskFile1 -> taskFileVos.add(new TaskFileVo(taskFile1)));System.out.println(taskFileVos);return AjaxResult.success(taskFileVos);}/**/@PostMapping("/upload/updateTaskFile")@Transactional(rollbackFor = Exception.class)public AjaxResult deleteFile(@RequestBody List<String> filePath) {try {for (String deleteFilePath : filePath) {taskFileService.deleteFilePath(deleteFilePath);FileUtils.deleteFile(deleteFilePath);}return AjaxResult.success("修改成功");} catch (Exception e) {System.out.println(e.getMessage());return AjaxResult.error(e.getMessage());}}/*** 本地资源通用下载*/@RequiresPermissions("system:task:export")@Log(title = "导出附件", businessType = BusinessType.EXPORT)@PostMapping("/download/resource")public void resourceDownload(String filePath, HttpServletRequest request, HttpServletResponse response) throws Exception {System.out.println(filePath);response.setCharacterEncoding("utf-8");response.setContentType("multipart/form-data");FileUtils.writeBytes(filePath, response.getOutputStream());}}