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