SpringBoot vue+axios文件上传与下载

2023-11-27 15:29:18 浏览数 (3)

上传

上传代码: 采用iview组件上传

代码语言:javascript复制
 <Upload :action="uploadApi" multiple
                  :headers="jwt"
                  :data="uploadData"
                  :on-success="uploadsuccess"
                  :on-error="uploadFaild"
                  :on-progress="uploadprogress"
                  :on-remove="removeFile"
          >

js

代码语言:javascript复制
 /*附件上传成功*/
    uploadsuccess( response, file, fileList){
      this.uploadIDs.push(response.aid)
      console.log(this.uploadIDs);
      file.uid=response.aid

    },
    /*附件上次失败*/
    uploadFaild(){

    },
    /*附件上传时*/
    uploadprogress(event, file, fileList){
      console.log(file);
      console.log(fileList);
    },
    /*移除文件*/
    removeFile(file, fileList){
      this.uploadIDs.splice(file.aid,1)
      console.log(this.uploadIDs);
    },

后台上传代码

代码语言:javascript复制
	@Autowired
    UploadService uploadService;
    @PostMapping("/uploadAttachment")
    public Attachment uploadAttachment(@RequestParam MultipartFile file, Attachment attachment){
        String md5ToId = Md5Util.md5ToId();
        attachment.setAid(md5ToId);
        String uploadPath = new Props("path.properties").get("uploadPath").toString();
        String path=uploadPath md5ToId;
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        path ="/" file.getOriginalFilename();//上传路径
        try {
            file.transferTo(new File(path));
            attachment.setAttpath(path);
            //添加数据库
            String filename = file.getOriginalFilename();
            attachment.setAttname(filename);
            attachment.setAttcreatetime(new Date());
            uploadService.InsertUpload(attachment);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return attachment;
    }

下载

下载代码 前端: 重点是axios 返回的类型需要配置{responseType:“blob”} 否则下载的文件格式会错误

代码语言:javascript复制
/*附件下载*/
    download(attids){
      var _this=this;
      var split = attids.split(",");
      split.forEach(function (item) {
        if(item!==""){
          var data={
            attid:item
          }
          _this.$axios.post(api 'upload/downloadFile',qs.stringify(data),{responseType:"blob"}).then(res=>{
            console.log(res.headers.filename);
            let content=res.data;
            console.log(res.data);
            var elink = document.createElement("a");
            elink.download=res.headers.filename;
            elink.style.display='none';
            let blob = new Blob([content]);
            elink.href=URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click()
            document.body.removeChild(elink)
          }).catch(err=>{
            console.log(err);
            this.$message.warning("请求错误!")
          })
        }
      })

    }

后台代码

代码语言:javascript复制
 @PostMapping("/downloadFile")
    public ResponseEntity<byte[]> downloadFile(String attid){
        Attachment attachment = new Attachment();
            attachment.setAid(attid);
            Attachment attachments = uploadService.getAttachments(attachment);
            String attpath = attachments.getAttpath();
            String name=attachments.getAttname();
            try {
                FileInputStream io = new FileInputStream(attpath);
                byte[] body = new byte[io.available()];
                io.read(body);
                HttpHeaders httpHeaders = new HttpHeaders();
                String filename = URLEncoder.encode(attachments.getAttname(), "UTF-8");
                httpHeaders.add("Content-Disposition","attachment;filename=" filename);
                httpHeaders.add("FileName",name);
                List<String> list = new ArrayList<>();
                list.add("FileName");
                httpHeaders.setAccessControlExposeHeaders(list);
                HttpStatus ok = HttpStatus.OK;
                ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, httpHeaders, ok);
                io.close();
                return responseEntity;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
    }

0 人点赞