一、简介
Spring Boot默认使用springMVC包装好的解析器进行上传
二、代码实现
2.1、from表单
1
2
3
4
|
<
form
method
=
"POST"
enctype
=
"multipart/form-data"
action
=
"/file/upload"
>
文件:<
input
type
=
"file"
name
=
"roncooFile"
/>
<
input
type
=
"submit"
value
=
"上传"
/>
</
form
>
|
2.2、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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package
com.example.demo.controller;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
import
org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestParam;
import
org.springframework.web.bind.annotation.ResponseBody;
import
org.springframework.web.multipart.MultipartFile;
import
java.io.File;
import
java.io.IOException;
/**
* 文件上传
* @Author: 我爱大金子
* @Description: 文件上传
* @Date: Created in 11:08 2017/6/18
*/
@Controller
@RequestMapping
(value =
"/file"
)
public
class
FileController {
private
static
final
Logger logger = LoggerFactory.getLogger(FileController.
class
);
@RequestMapping
(value =
"/upload"
)
@ResponseBody
public
String upload(
@RequestParam
(
"roncooFile"
) MultipartFile file) {
if
(file.isEmpty()) {
return
"文件为空"
;
}
// 获取文件名
String fileName = file.getOriginalFilename();
logger.info(
"上传的文件名为:"
+ fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf(
"."
));
logger.info(
"上传的后缀名为:"
+ suffixName);
// 文件上传路径
String filePath =
"G:/workspace/file_space/img/"
;
// 解决中文问题,liunx 下中文路径,图片显示问题
//fileName = UUID.randomUUID() + suffixName;
File dest =
new
File(filePath + fileName);
// 检测是否存在目录
if
(!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try
{
file.transferTo(dest);
return
"上传成功"
;
}
catch
(IllegalStateException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
return
"上传失败"
;
}
}
|
2.3、application.properties
1
2
3
4
5
6
7
8
9
10
|
#默认支持文件上传
spring.http.multipart.enabled=true
#支持文件写入磁盘.
spring.http.multipart.file-size-threshold=0
#上传文件的临时目录
spring.http.multipart.location=G:/workspace/file_space/temp
# 最大支持文件大小
spring.http.multipart.max-file-size=1Mb
#最大支持请求大小
spring.http.multipart.max-request-size=10Mb
|
三、测试
本文转自我爱大金子博客51CTO博客,原文链接http://blog.51cto.com/1754966750/1939485如需转载请自行联系原作者
我爱大金子