【Spring Boot】文件的上传
本文最后更新于 1523 天前,其中的信息可能已经有所发展或是发生改变。

1.编写一个上传用到的类。
[sourcecode language=”java” title=”Upload.java”]
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

import org.springframework.web.multipart.MultipartFile;

public class Upload {
/*
* file:上传的文件
* filePath:上传的路径
* fileName:文件的名称
*/
public static String upload(MultipartFile file, String filePath, String fileName) {
if(file.isEmpty()){
return null;
}
try {
// 获取文件名
String fileNameNew = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName=fileNameNew.substring(fileNameNew.lastIndexOf("."));
fileNameNew = fileName + suffixName;
// 上传后的文件路径名全称
File dest = new File(URLDecoder.decode(filePath + fileNameNew,"UTF-8"));
// 检测是否存在目录
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return fileNameNew;
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

}

}
[/sourcecode]
2.用上这个类从前台拿到文件给到上面的类处理就行,返回的值是文件的名字全称(包括文件类型)然后存入数据库就行。
但是我们会发现如果我们把文件上传到项目的static里面会发现页面刷新看不到文件,需要刷新一下文件夹,我们用下面的映射类映射一下文件就好。
[sourcecode language=”java” title=”PicConfig.java”]
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class PicConfig implements WebMvcConfigurer {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//前面的那个是映射后的前台引用的路径,后面那个是映射的本地路径。
registry.addResourceHandler("/imgs/user/**").addResourceLocations("file:C:/APP/java/spring boot/eclipse-workspace/liuliu/src/main/resources/static/imgs/user/");
}
}
[/sourcecode]
3.配置上传文件的大小限制。
[sourcecode language=”xml” title=”application.properties”]
#配置文件传输
spring.servlet.multipart.enabled =true
spring.servlet.multipart.file-size-threshold =0
#单个文件的最大上限
spring.servlet.multipart.max-file-size = 10MB
#单个请求的文件总大小上限
spring.servlet.multipart.max-request-size=100MB
[/sourcecode]
4.调用案例。
[sourcecode language=”java” title=”demo.java”]
//prostoreFile为上传的文件,benzhu为重命名的名字
String productStoreLicense = Upload.upload(prostoreFile, "C:\\APP\\java\\spring boot\\eclipse-workspace\\liuliu\\src\\main\\resources\\static\\imgs\\user\\", "benzhu"));
[/sourcecode]

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇