SpringBoot+Vueでファイルアップロード機能を実装

目次

1. バックエンドコード部分:

2. フロントエンドコード部分

3.エフェクト表示

1. バックエンドコード部分:

@RestController
@RequestMapping("/file")
public class FileController {
    private final String UPLOAD_PATH = "D:/OBS/";//这里写上你需要上传的路径(模拟服务器)

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam MultipartFile file) {
        // ... File upload logic ...
        if (file.isEmpty()) {
            return new ResponseEntity<>("文件不能为空", HttpStatus.BAD_REQUEST);
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_PATH + File.separator + file.getOriginalFilename());
            Files.write(path, bytes);
            return new ResponseEntity<>("文件上传成功", HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("文件上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

2. フロントエンドコード部分

<template>
    <div>
      <el-upload
        drag
        action="http://localhost:8081/file/upload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">拖拽文件到此处上传</div>
      </el-upload>
    </div>
  </template>

  <script>
export default {

  methods: {
    handleUploadSuccess(response, file) {
      this.$message.success('文件上传成功');
    },
    handleUploadError(err, file) {
      this.$message.error('文件上传失败');
    }
    
  }
};
</script>

3.エフェクト表示

 

 

 

おすすめ

転載: blog.csdn.net/Kristabo/article/details/131534089