VUE+Element+Spring Cloud implements file upload function (upload) + file deletion function (remove) + configures spring cloud file upload path

File upload function (upload) + file delete function + configure spring cloud file upload path

Problem Description

Recently, I encountered the file upload function in the project. I came into contact with vue element for the first time. I want to commemorate the development process and the small pit.
Not much to say, the code has been prepared. Please indicate the source for reprinting.

Vue front-end control code

div code file upload + delete


<div style="width: 15%;height:10%;marging-top:-15px">
      <el-col span="3">
         <el-button size='small' type="primary" @click="file">文件上传<i class="el-icon-upload el-icon--right"></i></el-button>
       </el-col>
       <el-dialog
         title="附件管理"
         :visible.sync="fileupload"
         width="30%"
         :before-close="handleClose"
       >
            <span>
                <el-upload
                  class="upload-demo"
                  drag
                  multiple
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :http-request="uploadSectionFile"
                >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处,或
                    <em>点击上传</em>
                  </div>
                </el-upload>
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">确定</el-button>
            </span>
       </el-dialog>
 </div>

js code

//定义弹窗的是否展示
 data() {
    
    
    return {
    
    
      fileupload: false
      }
 }
//单击文件上传按钮时,展示弹窗
file() {
    
    
  this.fileupload = true;
},
//文件上传具体过程,通过form表单提交
uploadSectionFile: function(param) {
    
    
  let file = param.file;
  //通过路径访问本地的文件下载方法
  let controller = "http://localhost:1111/upload/uploadFile";
  let form = new FormData();
  form.append("file", file);
  form.append("id", param.file.uid);
  let xhr = new XMLHttpRequest();
  xhr.open("post", controller, true);
  xhr.send(form);
},
//单击确定按钮或单击弹窗外的部分后弹窗隐藏,并自动刷新当前页
handleClose(done) {
    
    
  this.fileupload=false;
  this.loadFileTalbe();//该方法为页面初始化时数据表格查询展示的功能,不做过多赘述,理解为表格页面刷新功能。
},
//弹窗内删除文件时的提示确认功能
beforeRemove(file, fileList) {
    
    
  return this.$confirm(`确定移除 ${
      
      file.name}?`);
},
//删除功能的具体展示
handleRemove(file, fileList) {
    
    
	//removeFile为访问java端的api链接,参数uid为element上传控件自带的 id
  removeFile({
    
    id:file.uid}).then(resp => {
    
    
    if (resp && resp.data) {
    
    
      if (resp.data == true) {
    
    
        this.$message({
    
    
          showClose: true,
          message: "删除成功!",
          type: "success"
        });
      } else {
    
    
        this.$message({
    
    
          showClose: true,
          message: "删除失败!",
          type: "error"
        });
      }
    }
  }).catch(error => {
    
    
    console.log("error", error.message);
  })
}
//vue界面书写完成

java side spring cloud file code

java side code

@Controller
@RequestMapping("/upload")
public class UploadController {
    
    

    @Autowired
    private UploadService uploadService;
    //保存路径为D盘fj文件夹下
    public static  String STATIC_PATH = "D:/fj/";
    @CrossOrigin
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(@RequestBody MultipartFile file,
                             @RequestParam(value = "id", required = false) String id) {
    
    
        if (file.isEmpty()) {
    
    
            return "文件为空";
        }
        // 获取文件名
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String sj=dateFormat.format(date);
        //原文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //新名字(重复文件名问题)格式为:时间+原名文件名称
        String newname=sj+fileName;
        // 文件上传路径
        String filePath = STATIC_PATH +newname;
        //创建文件夹
        File dest = new File(filePath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
    
    
            dest.getParentFile().mkdirs();
        }
        try {
    
    
        	//文件保存到本地
            file.transferTo(dest);
            Map param = new HashMap();
            param.put("id", id);
            param.put("newname", newname);
            param.put("foldername", fileName);
            //数据库中保存需要的参数,具体流程不做赘述,根据业务需求自行实现
            uploadService.fjgl(param);
            return "上传成功";
            } catch (IllegalStateException e) {
    
    
                e.printStackTrace();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
            return "上传失败";
    }

So far, the functions of saving files to the local and saving file names to the database have been fully realized

Show results

upload image
The file deletion function display in the pop-up window (the deletion function is realized according to the uid automatically generated by the plug-in)
File delete function operation
successfully deleted

Configure spring cloud file upload path

In the example above, we use the static static constant to define the absolute path of saving the file. You
can also modify the configuration file to change the upload path of the file. The method is as follows
1. The content of the bootstrap.yml configuration file is as follows

ws:
  excelTemplateDpwloadPath: D:\fj\

2. Add configuration path class

@Component
@ConfigurationProperties(prefix = ConfigProperties.PREFIX)
public class ConfigProperties {
    
    
    public static final String PREFIX = "ws";

    private String excelTemplateDpwloadPath;

    public String getExcelTemplateDpwloadPath() {
    
    
        return excelTemplateDpwloadPath;
    }

    public void setExcelTemplateDpwloadPath(String excelTemplateDpwloadPath) {
    
    
        this.excelTemplateDpwloadPath = excelTemplateDpwloadPath;
    }
}

3. Call path

 @Autowired
 private ConfigProperties configProperties;
 //设置文件路径
 String realPath = configProperties.getExcelTemplateDpwloadPath();//这里使用配置类配置文件路径

write at the end

The author is new to the vue element framework, and it is still in the development stage for Baidu programming.
In order to realize the file upload function of this article, I have referred to the blogs of many bloggers, and I would like to express my heartfelt thanks to the seniors.
A link to the reference is attached. If there is any infringing content, please contact the author in time to delete
the reference

Use the upload component of element to implement a complete file upload function (Part 1)
Use yml configuration files and configuration classes in SpringBoot to modify file upload and download paths

File download here

Vue+element+spring cloud file download (download) function

Guess you like

Origin blog.csdn.net/qq_41648113/article/details/106472162