SpringBoot vue+axios文件上传与下载

2022-07-17 08:16:24

上传

上传代码:
采用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);},

后台上传代码

@AutowiredUploadService uploadService;@PostMapping("/uploadAttachment")publicAttachmentuploadAttachment(@RequestParamMultipartFile file,Attachment attachment){String md5ToId=Md5Util.md5ToId();
        attachment.setAid(md5ToId);String uploadPath=newProps("path.properties").get("uploadPath").toString();String path=uploadPath+md5ToId;File dir=newFile(path);if(!dir.exists()){
            dir.mkdirs();}
        path+="/"+file.getOriginalFilename();//上传路径try{
            file.transferTo(newFile(path));
            attachment.setAttpath(path);//添加数据库String filename= file.getOriginalFilename();
            attachment.setAttname(filename);
            attachment.setAttcreatetime(newDate());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=newBlob([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")publicResponseEntity<byte[]>downloadFile(String attid){Attachment attachment=newAttachment();
            attachment.setAid(attid);Attachment attachments= uploadService.getAttachments(attachment);String attpath= attachments.getAttpath();String name=attachments.getAttname();try{FileInputStream io=newFileInputStream(attpath);byte[] body=newbyte[io.available()];
                io.read(body);HttpHeaders httpHeaders=newHttpHeaders();String filename=URLEncoder.encode(attachments.getAttname(),"UTF-8");
                httpHeaders.add("Content-Disposition","attachment;filename="+filename);
                httpHeaders.add("FileName",name);List<String> list=newArrayList<>();
                list.add("FileName");
                httpHeaders.setAccessControlExposeHeaders(list);HttpStatus ok=HttpStatus.OK;ResponseEntity<byte[]> responseEntity=newResponseEntity<>(body, httpHeaders, ok);
                io.close();return responseEntity;}catch(FileNotFoundException e){
                e.printStackTrace();returnnull;}catch(IOException e){
                e.printStackTrace();returnnull;}}
  • 作者:Joker_DJ dear
  • 原文链接:https://blog.csdn.net/jokerdj233/article/details/120193869
    更新时间:2022-07-17 08:16:24