Vue3+AntDesign+SpringBoot处理多个文件(TXT)的上传,接收,读取

技术栈

  1. 前端用的是Vue3+Antdesign
  2. 后端用的是SpringBoot

使用场景

在前端上传多个文件(本例子是txt文件),后端接受之后并读取txt的内容。

前端代码

我没有把全部的代码贴上来哈,如果大家想看完整的,可以参考Antdesign官方给出的,我这里的使用场景跟官网的有一点点不太一样。我只把关键的代码贴了一下。

我这里的使用场景是用户上传了多个文件之后,再点击一个“Start Upload”按钮,才会把文件传到后端。

以下是UI组件的代码:

  <a-upload-dragger
    :file-list="fileList"
    :multiple="true"
    :before-upload="beforeUpload"
    @remove="handleRemove"
    name="file"
  >
    <p class="ant-upload-drag-icon">
      <inbox-outlined></inbox-outlined>
    </p>
    <p class="ant-upload-text">Click or drag file to this area to upload</p>
    <p class="ant-upload-hint">
      Support for a single or bulk upload. Strictly prohibit from uploading company data or other
      band files
    </p>
  </a-upload-dragger>
  <a-button
    type="primary"
    :disabled="fileList.length === 0"
    :loading="uploading"
    style="margin-top: 16px"
    @click="handleUpload"
  >
    {{ uploading ? 'Uploading' : 'Start Upload' }}
  </a-button>

以下是前端上传文件的调用方法

    const handleRemove = file => {
      const index = fileList.value.indexOf(file)
      const newFileList = fileList.value.slice()
      newFileList.splice(index, 1)
      fileList.value = newFileList
    }

    const beforeUpload = file => {
      fileList.value = [...fileList.value, file]
      return false
    }

    const handleUpload = async () => {
      const formData = new FormData()
      fileList.value.forEach(file => {
        // 注意这里append的名字“file”,需要跟后端接受的名字是一样的
        formData.append('file', file)
      })
      uploading.value = true 
      // 这里的axios换成大家熟悉的写法就可以,主要是formData是放到body里面的
      await APIService.post('/upload/xxx', formData).then((res) => {
        console.log(res)
      })
      
    }

后端代码

我不写那么复杂,严格的分controller和service,目的是给大家看如何接收到文件并且读取文件。大家可以根据自己的实际情况去调整。

需要注意的是@RequestParam(value = "file")的file是要跟前端的append的那么file是要保持一致的。

    @PostMapping("upload")
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public void upload(@RequestParam(value = "file") MultipartFile[] files) throws IOException {
        for (MultipartFile file : files) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String lineTxt;
            while ((lineTxt=bufferedReader.readLine())!=null){
                System.out.println(lineTxt);
            }
        }
    }

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值