SpringBoot配置文件

后端写一个Controller接收

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
package io.github.swzdl.uploaddemo.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class uploadController {
@CrossOrigin(origins = "*")
@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile[] file, HttpServletRequest request)
throws IllegalStateException, IOException {
for (MultipartFile f : file) {
String old_name = f.getOriginalFilename(); // 原始文件名
System.out.println(old_name);
String ext_name = old_name.substring(old_name.lastIndexOf(".")); // 扩展名
String new_name = new Date().getTime() + ext_name;
String path = "C:\\Users\\Sheng\\IdeaProjects\\upload-demo\\upload-demo\\src\\main\\resources\\";
File fx = new File(path);
if (!fx.exists()) {
fx.mkdirs();
}
File n = new File(fx, new_name);
f.transferTo(n);
}
}
}

需要配置最大上传文件大小:

1
2
3
server.port=8888
spring.servlet.multipart.max-file-size= 50MB
spring.servlet.multipart.max-request-size= 50MB

前端上传组件

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
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>文件上传Demo</title>
</head>

<body>
<div id="app">
<el-upload class="upload-demo" drag action="http://localhost:8888/upload" :data="uploadData"
:before-upload="setFileName" style="position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);">
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">文件不能超过 50 MB</div>
</el-upload>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new Vue({
el: "#app",
data: {
uploadData: {
fileName: new Date().getTime()
}
},
methods: {
setFileName(file, fileList) {
this.fileName = file.name
}
}
})
</script>

</body>

</html>

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×