java 文件表创建及前后端使用

====表结构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;
    }




    @Override
    public String toString() {
        return "TaskVo{" +
                "taskFileVos=" + taskFileVos +
                '}';
    }
}

==============

复制代码
@RestController
@RequestMapping("/taskFile")
public class TaskFileController {

    @Autowired
    private 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/uploadPath
            String 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());
    }






}
相关推荐
这个昵称不容易3 分钟前
SpringBoot「衣依」服装销售平台:144个Java文件180个接口,从挑衣服到收货评价整条链路都在
java·springboot·毕设
计算机毕设定制辅导-无忧学长24 分钟前
《基于微信小程序的居家医疗陪护预约系统设计与实现》
java·spring boot·微信小程序·uniapp·居家医疗陪护预约系统
张张123y38 分钟前
DSH 插件调试避坑:client.js 设置面板、热重载与高频报错排查表
开发语言·javascript·人工智能·开源·ecmascript·后端开发·ai agent
文丑颜不良啊2 小时前
LeetCode2221~2240题目解析
java·leetcode
秋饼2 小时前
Computer Use Agent Java 落地实战:感知-行动循环、执行器与安全围栏生产级实现
java·ai·技术分享·后端开发
冻柠檬飞冰走茶4 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊4 小时前
LeetCode2161~2180题目解析
java·leetcode
FRing034 小时前
vue2干货总结7(自定义指令、插槽、单页应用程序、路由的使用(VueRouter))
开发语言·前端·vue.js·vue2
雪落漂泊4 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
波力海苔夹心脆6755 小时前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典