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());
    }






}

  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要实现Java+Vue的家谱前后端分离系统,可以分为以下几个步骤: 1. 设计数据库结构:可以设计Person来存储每个人的信息,包括姓名、性别、父亲ID、母亲ID等字段。 2. 创建Java后端API:使用Spring Boot框架创建后端API,提供获取所有人、获取某个人、添加人等接口,通过JPA或MyBatis等框架操作数据库。 3. 创建Vue前端页面:使用Vue框架创建前端页面,包括家谱的展示、添加人、查找人等功能,使用axios等库调用后端API获取数据或提交数据。 以下是Java+Vue实现家谱前后端分离系统的示例代码: Java后端API: ```java @RestController @RequestMapping("/api") public class FamilyTreeController { @Autowired private PersonRepository personRepository; @GetMapping("/people") public List<Person> getAllPeople() { return personRepository.findAll(); } @GetMapping("/person/{id}") public Person getPerson(@PathVariable Long id) { return personRepository.findById(id).orElse(null); } @PostMapping("/person") public Person addPerson(@RequestBody Person person) { return personRepository.save(person); } } ``` Vue前端页面: ```html <template> <div> <h1>家谱</h1> <ul> <li v-for="person in people" :key="person.id"> {{ person.name }} <ul> <li v-for="child in getChildren(person)" :key="child.id"> {{ child.name }} </li> </ul> </li> </ul> <div> <h2>添加人</h2> <form @submit.prevent="addPerson"> <label>姓名:</label> <input type="text" v-model="newPerson.name"> <label>性别:</label> <select v-model="newPerson.gender"> <option value="male">男</option> <option value="female">女</option> </select> <label>父亲:</label> <select v-model="newPerson.fatherId"> <option v-for="person in people" :value="person.id" :key="person.id"> {{ person.name }} </option> </select> <label>母亲:</label> <select v-model="newPerson.motherId"> <option v-for="person in people" :value="person.id" :key="person.id"> {{ person.name }} </option> </select> <button type="submit">添加</button> </form> </div> </div> </template> <script> import axios from 'axios'; export default { data() { return { people: [], newPerson: { name: '', gender: 'male', fatherId: null, motherId: null } } }, created() { this.loadPeople(); }, methods: { loadPeople() { axios.get('/api/people') .then(response => { this.people = response.data; }); }, getChildren(person) { return this.people.filter(p => p.fatherId == person.id || p.motherId == person.id); }, addPerson() { axios.post('/api/person', this.newPerson) .then(response => { this.people.push(response.data); this.newPerson = { name: '', gender: 'male', fatherId: null, motherId: null }; }); } } } </script> ``` 在上面的代码中,`FamilyTreeController`类是Java后端API的实现,提供获取所有人、获取某个人、添加人等接口。`vue`文件是Vue前端页面的实现,包括家谱的展示、添加人等功能。通过axios等库调用后端API获取数据或提交数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

20岁30年经验的码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值