SpringBoot vue+axios文件上传与下载

上传

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

 <Upload :action="uploadApi" multiple
                  :headers="jwt"
                  :data="uploadData"
                  :on-success="uploadsuccess"
                  :on-error="uploadFaild"
                  :on-progress="uploadprogress"
                  :on-remove="removeFile"
          >
		  
		  

js

 /*附件上传成功*/
    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);
    },

后台上传代码

	@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”} 否则下载的文件格式会错误

/*附件下载*/
    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("请求错误!")
          })
        }
      })

    }

后台代码

 @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;
            }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值