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

1.前端上传代码

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

onexceed 文件超出个数限制时的钩子 function(files, fileList)
onchange 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用 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"&gt;
                <el-button size="small" type="primary"&gt;点击上传</el-button&gt;
                <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() &amp;&amp; !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() &amp;&amp; !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() &amp;&amp; file.isFile() &amp;&amp; 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() &amp;&amp; file.isFile() &amp;&amp; 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));
 
    },

完结撒花

本人小菜鸡一枚

原文地址:https://blog.csdn.net/qq_38599266/article/details/129893193

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_18835.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注