vue+element ui 封装一个简单的文件上传下载(常规方法)

vue+element ui 封装一个简单的文件上传下载(前端部分)

<template>
  <div>
    <!--
            list-type:  文件列表的类型	string	text/picture/picture-card	
            action :  必选参数,上传的地址	string
            :accept :  接受上传的文件类型
            :limit : 最大允许上传个数
            :on-exceed : 文件超出个数限制时的钩子
            :on-preview : 点击文件列表中已上传的文件时的钩子
            :on-remove : 文件列表移除文件时的钩子
            :before-upload : 上传文件之前的钩子
            :file-list : 上传的文件列表 array
            :auto-upload : 是否在选取文件后立即进行上传

            :data: 上传时附带的额外参数
            :multiple : 是否支持多选文件
            :show-file-list: 是否显示已上传文件列表 boolean
            :on-success: 文件上传成功时的钩子

            :headers="Myhead" 设置上传头
          -->
    <el-upload
      list-type="picture-card"
      ref="upload"
      :action="uploadUrl"
      :accept="acceptFileType"
      :limit="img_num"
      :data="datatype"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :auto-upload="true"
      :headers="Myhead"
      :show-file-list="showFileList"
      :on-success="handleUploadSuccess"
      :multiple="multiplestate"
      @change="imgblur"
    >
      <i class="el-icon-plus"></i>
      <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件,且不超过1MB
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible"  :append-to-body='true'>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "imgupload",
  props: {
    pngurl: {
      //父组件传进来的默认值
      default: "",
    },
    imgnum: {
      //父组件传进来的默认值
      default: 1,
    },
    type: {
      //父组件传进来的默认值
      default: "logo",
    },
  },
  data() {
    return {
      multiplestate: false,
      img_num: this.imgnum,
      datatype: { type: this.type },
      imageUrl: "",
      uploadUrl: "http://localhost:8089/renren-fast/file/uploadForType",

      uploadTemplateDialog: false,
      fileList: [],
      uploadLoading: false,
      acceptFileType: "image/png, image/jpeg", // 设置上传文件类型
      downLoadLoading: "",

      dialogImageUrl: "",
      dialogVisible: false,

      showFileList: true,
    };
  },
  watch: {
    imgnum: {
      deep: true,
      handler(val) {
        console.log(val);
        if (val > 1) {
          this.multiplestate = true;
        }
      },
    },
    pngurl: {
      deep: true,
      handler(val) {
           this.fileList = [];
        if (val != null && val != "") {
          var arr = val.split(",");
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] != "") {
            console.log("arr[i] =" + arr[i]);
            this.fileList.push({
              name: arr[i],
              url: arr[i],
            });
          }
        }
        }
      },
    },
  },
  methods: {
    imgblur() {},
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {

      this.$message.warning("只能选择"+this.imgnum+"个文件!");
    },

    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      var del = file.url.substr(0, 4);
      console.log(del);
      var delurl = "";
      if (del == "http") {
        delurl = file.url;
      } else {
        delurl = file.response.path;
      }

      var arr = this.pngurl.split(",");
      var newurl = "";
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] == delurl) {
          console.log("delurl =" + delurl);
        } else if (arr[i] != "") {
          newurl += arr[i];
          console.log("i:" + i);
          if (i != arr.length - 1 && arr.length != 0) {
            newurl += ",";
          }
        }
      }
      this.$emit("update:pngurl", newurl);
      this.$emit("changeimg");
    },

    // 点击文件列表中已上传的文件时的钩子 ,  在 模态窗中显示
    handlePreview(file) {
      // console.log(file);
      console.log(file.url);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 上传文件之前的钩子
    beforeUpload(file) {
      var that = this;
      // console.log("file:",file)
      //文件类型
      var fileName = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (!(fileName == "png" || fileName == "jpg" || fileName == "jpeg")) {
        that.uploadTemplateDialog = false;
        that.$message({
          type: "error",
          showClose: true,
          duration: 3000,
          message: "文件类型不是.png/.jpg文件!",
        });
        return false;
      }

      //读取文件大小
      var fileSize = file.size;
      // console.log(fileSize);
      if (fileSize > 1048576) {
        that.uploadTemplateDialog = false;
        that.$message({
          type: "error",
          showClose: true,
          duration: 3000,
          message: "文件大于1M!",
        });
        return false;
      }

      // 上传时 的 遮罩
      that.downloadLoading = that.$loading({
        lock: true,
        text: "数据上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0,0,0,0.7)",
      });

      return true;
    },

    //文件上传成功时的钩子
    handleUploadSuccess(res, file) {
      // console.log(res)
      console.log("上传成功...");
      //   console.log(this.datatype);
      // 用于在页面回显 图片
      try {
        this.imageUrl = file.raw;
      } catch (error) {
        this.imageUrl = window.URL.createObjectURL(file.raw);
      }

      // console.log("this.imageUrl ", this.imageUrl  )

      this.downloadLoading.close();
      this.uploadLoading = false;
      //   console.log(res.path);

      this.showFileList = true;
      if (this.pngurl != null && this.pngurl != "") {
        var arr = this.pngurl.split(",");
      arr.push(res.path);
      var newurl = "";
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] != "") {
          newurl += arr[i];
          if (i != arr.length - 1 && arr.length != 0) {
            newurl += ",";
          }
        }
      }
      }else{
         var newurl = res.path;
      }
      this.$emit("update:pngurl", newurl);
      this.$emit("changeimg");
    },
  },
  computed: {
    Myhead: function () {
      return { token: this.$cookie.get("token") };
    },
  },
};
</script>
<style>
</style>

后端部分

package io.renren.modules.router.controller;



/**
 *
 *
 */
@RestController
@RequestMapping("file")
public class FileUpload {
    @Autowired
    private MyFlieUtil myFlieUtil;

    /**
     * 文件上传到硬盘的目录
     */
    @Value("${upload.path}")
    private String FILE_UPLOAD_DISK_PATH = "";


    @Value("${upload.webUrl}")
    private String UPLOAD_LOCAL_PATH_WEB_URL = "";

    @RequestMapping("/uploadForType")
    @ResponseBody
    public R uploadForType(@RequestParam("type")String type, @RequestParam("file") MultipartFile file) throws IOException {

        System.out.println("type = " + type);
        System.out.println("file => " + file.getOriginalFilename());
        System.out.println("UPLOAD_LOCAL_PATH_WEB_URL = " + UPLOAD_LOCAL_PATH_WEB_URL);
        if (file == null || file.isEmpty()) {
            System.out.println(" = " + "上传失败,请选择文件");
            return R.error("上传失败,请选择文件");
        } else {
            String path = myFlieUtil.saveFileForType(file, type);
            System.out.println("path = " + path);
            return R.ok().put("path", path).put("type", type);
        }
    }

}

工具类

package io.renren.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class MyFlieUtil {

    /**
     * 文件上传到硬盘的目录
     */
    @Value("${upload.path}")
    private  String FILE_UPLOAD_DISK_PATH = "";

    @Value("${upload.webUrl}")
    private  String UPLOAD_LOCAL_PATH_WEB_URL = "";
    /**
     * 预设文件名
     * @param picFile 上传的文件
     * @return 文件名
     */
    public String getFileName(MultipartFile picFile) {
        String picFileName = picFile.getOriginalFilename();
        String ext = picFileName.substring(picFileName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+ext;
        return fileName;
    }
    /**
     * 上传文件到硬盘
     * @param picFile 上传的文件
     * @return 文件名
     */
    public void uploadToDisk(MultipartFile picFile,String fileName,String filePath) {
        mkdirDir(filePath);
        if (!filePath.endsWith("/")) {
            filePath = filePath + "/";
        }
        File dest = new File(filePath+fileName);
        try {
            picFile.transferTo(dest);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.gc();
        }
    }
    /**
     * 如果目录不存在,则创建目录
     * @param destPath
     */
    private void mkdirDir(String destPath) {
        File destFile = new File(destPath);
        if (!destFile.exists()) {
            destFile.mkdirs();
        }
    }

    /**
     * @description 文件上传,保存在本地硬盘,返回文件请求路径
     * @param picFile
     * @return
     * @throws IOException
     */
    /**/
    public String saveFile(MultipartFile picFile) throws IOException {
        String location = null;
        String destName = "";
        if(!picFile.isEmpty()){
            //得到真实路径
            String fileName = picFile.getOriginalFilename();
            String kzm = fileName.substring(fileName.lastIndexOf("."));
            //要保存的文件名
            destName = UUID.randomUUID().toString()+kzm;
            //取得上传文件存储路径
            //File directory = new File("");// 参数为空
            //String path = directory.getCanonicalPath()+"/src/main/webapp"+Const.PIC_FILE;
            String path = FILE_UPLOAD_DISK_PATH;
            //如果上传文件存储路径不存在则创建一个
            File s2 = new File(path);
            if (s2.exists()==false) {
                s2.mkdirs();
            }
            //文件路径
            location = path+"/"+destName;
            try {
                picFile.transferTo(new File(location));
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String url = UPLOAD_LOCAL_PATH_WEB_URL + destName;
        return url;
    }

    /**
     * @description 文件上传,保存在本地硬盘,返回文件请求路径
     * @param picFile
     * @return
     * @throws IOException
     */
    /**/
    public String saveFileForType(MultipartFile picFile, String type) throws IOException {
        String location = null;
        String destName = "";
        if(!picFile.isEmpty()){
            //得到真实路径
            String fileName = picFile.getOriginalFilename();
            String kzm = fileName.substring(fileName.lastIndexOf("."));
            //要保存的文件名
            destName = UUID.randomUUID().toString()+kzm;
            //取得上传文件存储路径
            //File directory = new File("");// 参数为空
            //String path = directory.getCanonicalPath()+"/src/main/webapp"+Const.PIC_FILE;
            String path = FILE_UPLOAD_DISK_PATH + type + "/";
            //如果上传文件存储路径不存在则创建一个
            File s2 = new File(path);
            if (s2.exists()==false) {
                s2.mkdirs();
            }
            //文件路径
            location = path+"/"+destName;
            try {
                picFile.transferTo(new File(location));
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String url = UPLOAD_LOCAL_PATH_WEB_URL + type + "/" + destName;
        return url;
    }
}

yml文件中

upload:
  path: D:\upload\
  webUrl: http://127.0.0.1:8089/renren-fast/upload/
  temp:
   path: D:\upload\upload_tmp

7.2.2.图片显示

在后台 的项目中 要增加

其中 Const.UPLOAD_LOCAL_PATH 为 文件存储的本地路径

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**").addResourceLocations("file:" + Const.UPLOAD_LOCAL_PATH);
    }
}

只要 实体类的属性值为 : http://127.0.0.1:8900/renren-fast/upload/brand_logo/3b73aaa7-ec21-4601-9432-ecabf07750d7.jpg

    <template slot-scope="scope" >
      <img :src="scope.row.brandLogoPath"  style="width: 150px; height: 60px" />
    </template>

由于 没有传递 token 还要 关闭 shiro的权限控制 ShiroConfig 类

filterMap.put("/upload/**", "anon");
posted @ 2022-01-09 10:51  qiufengsk  阅读(747)  评论(0)    收藏  举报