[开发小记] Springboot + vue 实现文件上传

372 阅读2分钟

文件上传是我们作为开发者在日常工作中经常遇到的一个需求,各个流行的组件库中也都有现成的组件可以很方便的直接调用。具体的用法不再赘述,这里笔者主要展示如何打通前后台的上传逻辑。

这里我们的框架使用Spring,前端使用的是ElementPlus,这里我们就不多做描述。

细节如下:

  • 前端支持文件上传(主动)。
  • 后端接受,并存储。

本教程并不是初级教程,所以略过环境安装部分,有需要的可以自行伴读。

前端部分

前端我们需要引入Element-Plus和axios来完成本次上传,vue代码如下所示。首先action一定需要置空,然后auto-upload设置为false这样我们就可以自由的控制文件上传。

  <el-upload
      action=""
      multiple
      :on-exceed="handleExceed"
      :file-list="fileList"
      :auto-upload = "false"
      :on-change="fileUpload"
  >
    <el-button type="primary">Click to upload</el-button>
    <template #tip>
      <div class="el-upload__tip">
        jpg/png files with a size less than 500KB.
      </div>
    </template>
  </el-upload>

搞定组件部分,js部分逻辑如下所示。

const fileUpload = (file, fileList) => {
  const file1 = new FormData()
  file1.append('file', fileList[0].raw)
  file1.append("fileType", 'IMAGE');
  service.request('/file/upload', file1, 'POST', true).then(() => {
    console.log("上传成功")
  })
};
const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
      `The limit is 3, you selected ${files.length} files this time, add up to ${
          files.length + uploadFiles.length
      } totally`
  )
};

这里的service.request是由axios封装的请求工具类,我们需要关注一点细节即可,只要涉及到文件上传,我们需要设置Content-Type为form-data来完成上传。

if (type.toUpperCase() === 'POST') {
    headers = {
        'Content-Type': isFile ? 'multipart/form-data' : 'application/x-www-form-urlencoded'
    }
}

后端部分

后端部分就更加简单,我们只需要添加一个Spring Controller接口即可,我们需要关注的点就是文件上传所接收的就是MultipartFile,如果涉及到多文件上传,那么改为List即可。

@RestController
@RequestMapping("/file")
@CrossOrigin("*")
public class UploadController {

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
    public String upload(@RequestPart MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = fileName;

        File dest = new File(filePath);
        Files.copy(file.getInputStream(), dest.toPath());
        return "Upload file success : " + dest.getAbsolutePath();
    }
}