Vue.js上传下载前后端方法

本文详细介绍了使用Vue.js进行文件上传和下载的操作步骤,包括前端如何设置标签属性及调用方法,以及后端如何处理来自前端的上传和下载请求。

上传:
①前端:标签属性设置代码

  <el-upload
    class="upload-demo"
    name="file"
    action=""
    style="float:right;"
    accept=".dox,.docx,.dotx,.rtf"
    :before-upload="uploadFile"
    multiple
    :on-exceed="handleExceed">
    <kt-button icon="el-icon-upload2" :label="$t('action.upload')" :size="size" :perms="permsUpload"
               type="primary" v-if="showUpLoad" @click="fileUpload(scope.$index, scope.row)"/>
  </el-upload>

②前端:上传调用方法

uploadFile(file) {
        const isLt2M = file.size / 1024 / 1024 < 5
        if (!isLt2M) {
          this.$message.warning('上传附件大小不能超过 5MB!')
          return
        }
        var formData = new FormData();
        formData.append('file', file);
        formData.append('userId', this.userId);
        formData.append('name', sessionStorage.getItem('user'));
        var file = formData;
        this.$api.resume.upload(file).then((res) => {
          if (res.code == 200) {
            this.$message({message: "上传成功", type: 'success'})
            this.findPage()
          } else if (res.code == 401) {
            this.$message({
              message: '会话过期,请重新登录',
              type: 'error'
            })
            localStorage.clear();
            sessionStorage.clear();
            setTimeout(() => {
              this.$router.push('/login')
            }, 400)
          } else {
            this.$message
            this.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }
        })
        return false;
      },

③后端:上传请求服务器方法

@PreAuthorize("hasAuthority('sys:resume:upload')")
@PostMapping(value = "/upload")
public HttpResult upload(HttpServletRequest request,@RequestParam("userId") Long userId,@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
    if (Objects.isNull(file) || file.isEmpty())
        return HttpResult.error("文件为空,请重新上传");
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
        String fileName = file.getOriginalFilename();
        fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "(" + simpleDateFormat.format(System.currentTimeMillis()) + ")" + fileName.substring(fileName.lastIndexOf("."));
        byte[] bytes = file.getBytes();
        String path = request.getSession().getServletContext().getRealPath("/upload/attachment");
        Path paths = Paths.get(path, fileName);
        if (!Files.isWritable(paths)) {
            Files.createDirectories(Paths.get(path));
        }
        Files.write(paths, bytes);
        if(sysResumeService.upload(userId, fileName,name)!=0)
        return HttpResult.ok(sysResumeService.updateOperationTime(name,userId));
    } catch (IOException e) {
        return HttpResult.error(e.toString());
    }
    return HttpResult.ok();
}

下载:
①前端:标签属性设置代码

<kt-button :label="$t('action.batchDownload')" :perms="permsDownload" :size="size" type="primary"
                 @click="fileBatchDownload()"
                 :disabled="this.selections.length===0" style="float:left;" v-if="showDownLoad"/>

②前端:下载调用方法

fileBatchDownload: function () {
    let ids = this.selections.map(item => item.id).toString()
    this.fileDownload(ids)
  },
  fileDownload: function (ids) {
    let params = []
    let idArray = (ids + '').split(',')
    this.$api.resume.findUrlById(idArray).then(res => {
      if (res.msg == "") {
        this.$message.warning('选中用户不存在附件或附件已被删除,请重新选择!')
        return
      } else {
        // this.loading = true
        this.$message({message: '文件已开始下载,请等待下载完成', type: 'success'})
        this.$api.resume.batchDownload(idArray).then(response => {
          // this.loading = false
          if (!response) {
            this.$message.warning('下载失败,请重试!')
            return
          }
          let url = window.URL.createObjectURL(new Blob([response]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', res.msg)
          document.body.appendChild(link)
          link.click()
        }).catch((error) => {
        })
      }
    })
  },

③后端:下载请求服务器方法

@PreAuthorize("hasAuthority('sys:resume:download')")
    @PostMapping(value = "/download")
    public void download1(HttpServletRequest request,HttpServletResponse response, @RequestBody String[] idList) {
        if (idList.length != 0) {
            String path = request.getSession().getServletContext().getRealPath("/upload/attachment");
            String filename = "";
            File file = null;
            List<File> list = new ArrayList<>();
            for(String id : idList){
                List<SysResumeAttachment> sysResumeAttachments = sysResumeService.findAttachmentNameById(Long.parseLong(id));
                if (sysResumeAttachments.size() != 0) {
                    for (SysResumeAttachment sysResumeAttachment : sysResumeAttachments) {
                        File Subfile = new File(path + "/" + sysResumeAttachment.getAttachmentName());
                        if (Subfile.isFile() && Subfile.exists())
                            list.add(Subfile);
                    }
                }
            }
            if (list.size() != 1) {
                file = new File(path + "/xxx" + System.currentTimeMillis() + ".zip");
                ZipUtil.toZip(list, file);
            } else
                file = list.get(0);
            try {
                filename = file.getName();
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
                response.setHeader("FileName", filename);
                response.setHeader("Access-Control-Expose-Headers", "FileName");
                int len = 0;
                FileInputStream fs = new FileInputStream(file);
                PrintWriter writer = response.getWriter();
                while ((len = fs.read()) != -1) {
                    writer.write(len);
                }
                fs.close();
                writer.close();
                if (file.getName().endsWith(".zip") && file.exists())
                    file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值