vue+elementui + Spring boot项目实现文件上传下载

基于vue+elemenui的带来的前后端分离模式,实现文件图片上传服务器,下载到本地等操作

1.前端上传代码:

使用表单文件上传组件el-upload,通过:action绑定上传文件的api,此处我们将auto-upload设置为true,实现异步上传。以下几个方法可以自行查询elementui官方文档

on-exceed文件超出个数限制时的钩子function(files, fileList)
on-change文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用function(file, fileList)
on-success文件上传成功时的钩子function(response, file, fileList)
on-remove文件列表移除文件时的钩子function(file, fileList)
on-preview点击文件列表中已上传的文件时的钩子function(file)
accept接受上传的文件类型(thumbnail-mode 模式下此参数无效)string
 <el-form-item label="上传附件" >
              <el-upload
                class="upload-demo"
                :action="fileUpload()"
                v-model="fileUrl"
                multiple
                name="file"
                :limit="3"
                :auto-upload="true"
                :on-exceed="handleExceed"
                :on-change="handleChange"
                :on-remove="handleFileRemove"
                :on-success="handleSuccess"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
              </el-upload>
            </el-form-item>

js方法实现:

   handleSuccess(res, file, fileList){
    //图片上传成功后将图片数据存入数据库的方法
      console.log("res=>",res)
      console.log("file==>",file)
      let obj = new Object()
      obj.id = this.activeForm.id
      obj.file_url = res.message
      this.$post("/active/file/add", obj).then(re => {
        if (re.code==200){
          this.$notify.success({
            title: '消息',
            message: '文件上传成功!',
          } )
          this.fileList.push({
            name:file.name,
            url:file.response.message,
            uid:file.uid,
            status:'success'
          })
        }else {
          this.$notify.error({
            title: '消息',
            message: '文件上传失败!',
          } )
        }
      });
    },
    handleFileRemove(file,fileList){
   //图片删除方法直接调用后台方法,在后台删除图片
      console.log("file=>",file)
      let obj = new Object()
      obj.id = this.activeForm.id
      obj.file_url = file.url
      this.$post("/active/file/del", obj).then(re => {
        if (re.code==200){
          this.$notify.success({
            title: '消息',
            message: '文件删除成功!',
          } )
        }else {
          this.$notify.error({
            title: '消息',
            message: '文件删除失败!',
          } )
        }
      });
    },
    handleExceed(files, fileList){
      this.$notify.warning({
        title: '警告',
        message: '上传文件数量超过限制!',
      })
    },
    fileUpload(){
    //图片自动上传的api
      return this.$IPConfig.IpConfig + "/api/fileUpload";
    },

后端实现:此处我们将图片或文件直接存储在服务器D盘符下的fileUpload目录下

/**
     * csr文件上传
     * @param file 文件流
     * @param request
     * @return
     */
    @PostMapping("/api/fileUpload")
    public Result ImgUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        try {
        String path = "D:/fileUpload/";
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
        }

        //获取原始图片名(包含格式)
        String originalFileName = file.getOriginalFilename();
//        System.err.println("原始图片名称:" + originalFileName);

        //获取图片类型,以最后一个“.”为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
//        System.out.println("图片类型"+type);

        //获取图片名称(不含格式)
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
        if (name.contains(",")){
            name.replaceAll(","," ");
        }
        //设置图片的新名称:UUID+当前时间+文件名称(包含格式)
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(d);
        String fileName = UUID.randomUUID() + date + name + "." + type;
//        System.err.println("新图片名称:"+fileName);
        //在指定路径下创建图片夹
        File targetFile = new File(path, fileName);


            file.transferTo(targetFile);
//            System.out.println("图片上传成功!");
            return new Result(true, ServerPathUrl.ENV_URL + "/fileUpload/" + fileName);
//            return new Result(true,"http://192.168.119.30:8080/fileUpload/"+fileName);
        } catch (Exception e) {
//            System.err.println("图片上传失败!");
            e.printStackTrace();
            return new Result(false, "文件上传失败!");
        }
    }



 /**
     * 图片上传
     *
     * @param img
     * @param request
     * @return
     * @throws IOException
     */
    @ApiOperation("图片上传")
    @PostMapping("/api/imgUpload")
    public Result ImgUpload(@RequestParam("img") MultipartFile img, HttpServletRequest request) throws IOException {
        log.info("上传图片{}",img);
        String path = "D:/imgUpload/";
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
        }

        //获取原始图片名(包含格式)
        String originalFileName = img.getOriginalFilename();

        //获取图片类型,以最后一个“.”为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);

        //获取图片名称(不含格式)
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        //设置图片的新名称:UUID+当前时间+图片名称(包含格式)
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(d);
        String fileName = UUID.randomUUID() + date + name + "." + type;

        //在指定路径下创建图片
        File targetFile = new File(path, fileName);

        try {
            File originImg = PicUtils.multipartFileToFile(img);
            byte[] bytes = FileUtils.readFileToByteArray(originImg);
            long l = System.currentTimeMillis();
            //压缩后图片大小,图片小于300kb
            bytes = PicUtils.compressPicForScale(bytes, 300, "x");
            //压缩后图片存放地址
            FileUtils.writeByteArrayToFile(targetFile, bytes);
            //删除临时文件
            PicUtils.delTempFile(originImg);
            return new Result(true, ServerPathUrl.ENV_URL + "/upload/" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "图片上传失败!");
        }
    }

图片上传成功和删除图片的接口如下:

 @PostMapping("/active/file/add")
    public OutVO addFile(@RequestBody OutActive outActive){
        return  outActiveService.addFile(outActive);
    }

    @PostMapping("/active/file/del")
    public OutVO delFile(@RequestBody OutActive outActive){
        return  outActiveService.delFile(outActive);
    }

具体实现,图片添加成功后将返回图片完整路径:http://192.168.119.30:8080/fileUpload/"+fileName存入数据库,到时候读取图片直接通过路径读取

删除图片

  @Override
    public OutVO delFile(OutActive outActive) {
        log.info("进入【删除文件】操作{}",outActive);
        boolean flag = DelServiceResource.delOneReportImg(outActive.getFile_url());
        int row = activeFileMapper.delActiveFile(outActive.getId(), outActive.getFile_url());
        return OutVO.ok();
    }




DelServiceResource类是用来删除图片的工具类:

/**
     * 删除单张图片
     *
     * @param imgUrl 图片地址
     * @return
     */
    public static boolean delOneReportImg(String imgUrl) {
        imgUrl = imgUrl.replace(ServerPathUrl.ENV_URL+"/upload/", "D://imgUpload/");
        File file = new File(imgUrl);
        if (file.exists() && file.isFile() && file.delete()) {
           return true;
        } else {
            return false;
        }
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件地址
     * @return
     */
    public static boolean delScoreMaintainFile(String fileUrl) {
        fileUrl = fileUrl.replace(ServerPathUrl.ENV_URL+"/fileUpload/", "D://fileUpload/");
        File file = new File(fileUrl);
        if (file.exists() && file.isFile() && file.delete()) {
            return true;
        } else {
           return false;
        }
    }

前端需要显示图片,可以直接将存入数据库的url放入图片标签的url中,浏览器会自动去服务器获取图片并显示出来。

如果上传的是文件,那下载文件就需要专门的文件下载类来处理了:

/**
     * Description: 文件下载控制类
     *
     * @param path     文件地址
     * @param response
     */
    @GetMapping("/downloadFile")
    public void download(@RequestParam("url") String path, HttpServletResponse response) {
        try {
            // path: 目标文件的路径
            System.err.println(path);
            path = path.replace(ServerPathUrl.ENV_URL + "/fileUpload/", "D://fileUpload/");
//            path = path.replace("http://192.168.119.30:8080/fileUpload/", "D://fileUpload/");
            File file = new File(path);
            // 获取文件名 - 设置字符集            String downloadFileName = new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1");
            // 以流的形式下载文件
            InputStream fis;
            String fileName = path.substring(65, path.length());
//            System.err.println(fileName);
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Description: 文件下载控制类
     *
     * @param path     文件地址
     * @param response
     */
    @ApiOperation("文件下载")
    @GetMapping("/downloadBprFile")
    public void downloadBprFile(@RequestParam("url") String path, HttpServletResponse response) {
        try {
            // path: 目标文件的路径
            path = path.replace(ServerPathUrl.ENV_URL + "/bprFileUpload/", "D://bprFileUpload/");
//            path = path.replace("http://192.168.119.30:8080/fileUpload/", "D://fileUpload/");
            File file = new File(path);
            // 获取文件名 - 设置字符集            String downloadFileName = new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1");
            // 以流的形式下载文件
            InputStream fis;
            String fileName = path.substring(68, path.length());
//            System.err.println(fileName);
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

文件下载的前端代码:

<span @click="clickTest(item.url)" style="color: blue"><a class="dwn">下载</a></span>

js代码:

   //文件下载触发函数
    clickTest(item) {
  
      window.open(this.$IPConfig.IpConfig + "/api/downloadFile?url=" + encodeURIComponent(item));
 
    },

完结撒花

本人小菜鸡一枚

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值