Java springboot实现 小文件上传本地服务器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package io.github.lyr2000.dissertation.controller.test;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * @author lyr
 * @description fileTest
 * @create 2021-11-18 23:44
 */
@Slf4j
@RestController
@RequestMapping("/test/api/file")
@Profile("test")
public class FileTestController {
    @Value("D:/ASUS/Desktop/app/")
    private String FILE_DIR;
    @PostConstruct
    void init() {
        log.info("test 文件上传测试开启,本地测试路径: = {}",FILE_DIR);
    }



    @PostMapping("/upload")
    public String upload(@RequestPart("file")MultipartFile file) {
        String originName = file.getOriginalFilename();
        String destPath = FILE_DIR + '/' + originName;
        File dest = new File(destPath);
        try {
            file.transferTo(dest);
            return "上传成功";
        }catch (Exception e) {
            log.error("upload error = {}",e.getMessage());
        }
        return "上传失败!!!!";

    }


}

前端测试代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
 
</head>
<body>

  <form
    method="POST"
    action="/test/api/file/upload"
    enctype="multipart/form-data"
  >
    上传文件:
    <input multiple type="file" name="file"  placeholder="上传文件"/>
    <button type="submit">上传</button>
  </form>
  
  

  <script>

  </script>



</body>
</html>