每一秒钟的时间都值得铭记

0%

vue+SpringBoot实现文件上传

今天我们来学习使用Vue+SpringBoot来实现文件上传,其实今天的重点在于前端使用Vue获取文件,并传输到后台,至于后台上传文件则是通用的代码。

Vue获取文件

  • upload.html

    前端我们使用了Vue.js,其中使用axios来发送异步请求。

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
<div id="app">
<input type="file" @change="getFile($event)">
<input type="button" value="上传" @click="upload()">
</div>
</body>
<script>
const app = new Vue({
el: "#app",
data: {
formData: new FormData(),
},
methods: {
upload() {
axios.post("/upload/image",this.formData).then(resp => {
if (resp.status == 200) {
alert("success");
}
});
},
getFile(event) {
let file = event.target.files[0];
let fileName = file.name;
let index = fileName.lastIndexOf(".");
if (index != -1) {
let suffix = fileName.substr(index + 1).toLowerCase();
if (suffix == 'png' || suffix == 'jpg') {
this.formData.append("file",file);
}
}
}
}
})
</script>

后台项目依赖

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
<!--SpringBoot的启动器-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent>

<dependencies>
<!--SpringMVC的启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--用来处理文件上传的一个通用工具类-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!--lombox插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>

文件上传相关配置

  • application.yml

    1
    2
    3
    4
    5
    6
    7
    8
    file:
    upload:
    path: G:\temp\images\ #文件上传目标路径
    allowTypes: #文件上传允许的类型
    - image/jpeg
    - image/png
    - image/jpg
    - image/bmp
  • UploadProperties.java

1
2
3
4
5
6
7
8
9
10
11
12
/**
* 图片上传的Java配置类,通过SpringBoot自动读取配置文件注入
*/
@Data
@Component
@ConfigurationProperties(prefix = "file.upload")
public class UploadProperties {
// 图片上传路径
private String path;
// 文件上传允许类型
private List<String> allowTypes;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 图片上传的Java配置类
*/
@Configuration
public class UploadConfig {

@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 单个数据大小
factory.setMaxFileSize("10240KB");
/// 总上传数据大小
factory.setMaxRequestSize("102400KB");
return factory.createMultipartConfig();
}
}

文件上传后台代码

  • controller层
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @RestController
    @RequestMapping("upload")
    public class UploadController {

    @Autowired
    private UploadService uploadService;

    @PostMapping("image")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
    return ResponseEntity.ok(uploadService.uploadImage(file));
    }
    }
  • service层接口
1
2
3
4
5
6
7
8
9
10
public interface UploadService {

/**
* 上传图片
* @param file
* @return
* @throws Exception
*/
String uploadImage(MultipartFile file) throws Exception;
}
  • service层实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Service
public class UploadServiceImpl implements UploadService {

@Autowired
private UploadProperties uploadProperties;

@Override
public String uploadImage(MultipartFile file) throws IOException {
if(!uploadProperties.getAllowTypes().contains(file.getContentType())){
throw new IOException("文件上传类型错误!");
}
String fileName = UploadUtils.generateFileName(file.getOriginalFilename());
file.transferTo(new File(uploadProperties.getPath()+fileName));
return fileName;
}
}

文件上传工具类

  • IDUtils
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public class IDUtils {

    /**
    * 唯一ID生成器,可以生成唯一ID
    *
    * @return 唯一ID
    */
    public static String generateUniqueId() {
    return UUID.randomUUID().toString() + System.currentTimeMillis();
    }
    }
  • UploadUtils
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public class UploadUtils {

    /**
    * 文件名称替换工具,将文件名称替换为随机名称
    *
    * @param oldName 上传文件名字
    * @return 生成的新文件名
    */
    public static String generateFileName(String oldName) {
    String suffix = oldName.substring(oldName.lastIndexOf("."));
    return IDUtils.generateUniqueId() + suffix;
    }
    }
坚持原创技术分享,您的支持将鼓励我继续创作!
-------------这是我的底线^_^-------------