这篇文章主要介绍了vue怎么使用el-upload实现文件上传功能的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇vue怎么使用el-upload实现文件上传功能文章都会有所收获,下面我们一起来看看吧。
upload.vue
<template> <el-form> <el-form-item label="姓名" prop="name"> <el-input v-model="name"></el-input> </el-form-item> <el-form-item> <el-upload ref="upfile" :auto-upload="false" :on-change="handleChange" :file-list="fileList" action="#"> <el-button type="success">选择文件</el-button> </el-upload> </el-form-item> <el-form-item> <el-button type="success" @click="upload">点击上传</el-button> </el-form-item> </el-form> </template><script>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('失败') } }) }, }}</script>
springboot后台 uploadController.java
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,"文件找不到"); } } }
关于“vue怎么使用el-upload实现文件上传功能”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“vue怎么使用el-upload实现文件上传功能”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程网行业资讯频道。