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);
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/fenger_c/article/details/125181602
今日推荐