vue使用el

您所在的位置:网站首页 如何更改上传文件的文件类型 vue使用el

vue使用el

2023-06-20 07:28| 来源: 网络整理| 查看: 265

系列文章目录

文章目录 系列文章目录前言一、前台Vue二、后台Springboot总结

前言

因为我是vue+springboot前后分离,要跨域,就不能用默认的action写请求地址,我用axios时最困扰的就是怎么拿到那个真实的文件,然后给传给后台。

其实可以通过自带的onchanne触发方法获得文件列表,文件信息中那个raw就是真实的文件。

写的时候,刚开始我是直接把el-upload里面的button中加了点击事件,但是每次文件还没选,就已经向后台发出请求了,当然传不过去,于是外面套了个form。

element-ui组件使用可以查看文档

一、前台Vue 选择文件 点击上传 export default { name:'UploadUi', data(){ return{ name:'', fileList:[] } }, methods:{ //通过onchanne触发方法获得文件列表 handleChange(file, fileList) { this.fileList = fileList; console.log(fileList) }, upload(){ let fd = new FormData(); fd.append("name",this.name); this.fileList.forEach(item=>{ //文件信息中raw才是真的文件 fd.append("files",item.raw); //console.log(item.raw) }) this.$axios.post('/uploadUi',fd).then(res=>{ if (res.data.code === 200) { //console.log(res); this.$message('上传成功') }else{ this.$message('失败') } }) }, } } 二、后台Springboot package com.example.demo.controller; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.List; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.example.demo.entity.ListParam; import com.example.demo.entity.MyUser; import com.example.demo.entity.Result; @RestController @ResponseBody @CrossOrigin @RequestMapping("/api") public class UploadController { @PostMapping("/uploadUi") public Result upFile(@RequestParam("name")String name,@RequestParam("files") MultipartFile[] files ) { System.out.println("开始"); System.out.println(name); if(files != null) { for(MultipartFile file : files) { String fileName = file.getOriginalFilename(); System.out.println(fileName); try{ File mkdir = new File("F:\\app\\file"); if(!mkdir.exists()) { mkdir.mkdirs(); } //定义输出流,将文件写入硬盘 FileOutputStream os = new FileOutputStream(mkdir.getPath()+"\\"+fileName); InputStream in = file.getInputStream(); int b = 0; while((b=in.read())!=-1){ //读取文件 os.write(b); } os.flush(); //关闭流 in.close(); os.close(); }catch(Exception e) { e.printStackTrace(); return new Result(401,"失败"); } } return new Result(200,"成功"); }else { return new Result(401,"文件找不到"); } } } 总结

以上就是本文的全部内容,希望对大家的学习有所帮助

需要系统源码或者BiShe加V ID:talon712



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3