avatar

SpringBoot文件上传

摘要:本文介绍了在Springboot中如何进行文件上传,以及使用Ajax上传,以及多文件上传的方式

SpringBoot文件上传


使用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
package com.example.fileupload;

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

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
* @author: WJZheng
* @date: 2020/3/16 14:19
* @description:
*/
@RestController
public class FileUploadController {

SimpleDateFormat dateFormat = new SimpleDateFormat("/yyyy/MM/dd/");

@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest request) {
String format = dateFormat.format(new Date());
//完整的路径
String realPath = request.getServletContext().getRealPath("/img") + format;
//创建一个保存的文件夹
File folder = new File(realPath);
//若文件夹不存在,则创建该文件夹
if (!folder.exists()) {
folder.mkdirs();
}
//为了避免重名,需要修改上传文件的名字
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(folder, newName));
//动态获取上传文件的url
String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + format + newName;
System.out.println("submit success!");
return url;
} catch (IOException e) {
e.printStackTrace();
}
return "errors";
}
}

然后创建一个HTML页面用于上传

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="submit">
</form>
</body>
</html>

上传成功后返回文件的url,访问url即可看到上传的文件。

使用Ajax进行文件上传


使用Ajax进行文件上传,后台代码还是使用上面的代码,只是前端需要修改一下。

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">
<title>Title</title>
<script src="jquery-3.4.1.js"></script>
</head>
<body>
<div id="result"></div>
<input type="file" id="file">
<input type="button" value="submit" onclick="upload()">
<script>
function upload() {
//$("#file")[0]把jQuery对象转成JavaScript对象
var fileElement = $("#file")[0].files[0];
var formData = new FormData();
formData.append("file",fileElement);
$.ajax({
type:'post',
url:'/upload',
processData: false,
contentType: false,
data: formData,
success: function (msg) {
$("#result").html(msg);
}
})
}
</script>
</body>
</html>

SpringBoot多文件上传


多文件上传并不难,首先在前端页面的input标签里添加一个multiple属性,然后在后台代码中使用一个MultipartFile数组来处理即可。

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
package com.example.fileupload;

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

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
* @author: WJZheng
* @date: 2020/3/16 14:19
* @description:
*/
@RestController
public class FileUploadController {

SimpleDateFormat dateFormat = new SimpleDateFormat("/yyyy/MM/dd/");

@PostMapping("/uploads")
public String uploads(MultipartFile[] files, HttpServletRequest request) {
String format = dateFormat.format(new Date());
String realPath = request.getServletContext().getRealPath("/img") + format;
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
for (MultipartFile file : files) {
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(folder, newName));
String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + format + newName;
System.out.println(url);
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/uploads" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple>
<input type="submit" name="submit">
</form>
</body>
</html>

运行程序,然后选择多个文件并上传,我们可以看到控制台输出了上传文件的URL。

Author: WJZheng
Link: https://wellenzheng.github.io/2020/03/16/SpringBoot%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Comment