前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot vue+axios文件上传与下载

SpringBoot vue+axios文件上传与下载

作者头像
JokerDJ
发布2023-11-27 15:29:18
2480
发布2023-11-27 15:29:18
举报
文章被收录于专栏:JokerDJJokerDJ

上传

上传代码: 采用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;
            }
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-09-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 上传
  • 下载
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档