Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5630d07

Browse files
committed
add spring-boot-file-upload
1 parentd947015 commit5630d07

File tree

10 files changed

+256
-2
lines changed

10 files changed

+256
-2
lines changed

‎README.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,7 @@ Spring Boot 使用的各种示例,以最简单、最实用为标准,此开
4040
-[spring-boot-package](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-package):Spring Boot 3.0 单元测试、集成测试、打 Jar/War 包、定制启动参数使用案例
4141
-[spring-boot-web-thymeleaf](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-web-thymeleaf):Spring Boot 3.0 thymeleaf 增删该查示例
4242
-[spring-boot-jpa-thymeleaf-curd](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-jpa-thymeleaf-curd):Spring Boot 3.0 Jpa thymeleaf 列表、增删改查使用案例
43-
44-
43+
-[spring-boot-file-upload](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-file-upload):Spring Boot 3.0 上传文件使用案例
4544

4645

4746

‎spring-boot-file-upload/pom.xml‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<projectxmlns="http://maven.apache.org/POM/4.0.0"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
4+
http://maven.apache.org/maven-v4_0_0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.neo</groupId>
8+
<artifactId>spring-boot-file-upload</artifactId>
9+
<packaging>jar</packaging>
10+
<version>1.0</version>
11+
12+
<parent>
13+
<groupId>org.springframework.boot</groupId>
14+
<artifactId>spring-boot-starter-parent</artifactId>
15+
<version>3.0.0</version>
16+
<relativePath/><!-- lookup parent from repository-->
17+
</parent>
18+
19+
<properties>
20+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
21+
<java.version>17</java.version>
22+
</properties>
23+
24+
<dependencies>
25+
<dependency>
26+
<groupId>org.springframework.boot</groupId>
27+
<artifactId>spring-boot-starter-web</artifactId>
28+
</dependency>
29+
<dependency>
30+
<groupId>org.springframework.boot</groupId>
31+
<artifactId>spring-boot-starter-thymeleaf</artifactId>
32+
</dependency>
33+
</dependencies>
34+
35+
<build>
36+
<plugins>
37+
<plugin>
38+
<groupId>org.springframework.boot</groupId>
39+
<artifactId>spring-boot-maven-plugin</artifactId>
40+
</plugin>
41+
</plugins>
42+
</build>
43+
44+
</project>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
packagecom.neo;
2+
3+
importorg.apache.coyote.http11.AbstractHttp11Protocol;
4+
importorg.springframework.boot.SpringApplication;
5+
importorg.springframework.boot.autoconfigure.SpringBootApplication;
6+
importorg.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
7+
importorg.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
8+
importorg.springframework.context.annotation.Bean;
9+
10+
@SpringBootApplication
11+
publicclassFileUploadWebApplication {
12+
13+
publicstaticvoidmain(String[]args)throwsException {
14+
SpringApplication.run(FileUploadWebApplication.class,args);
15+
}
16+
17+
//Tomcat large file upload connection reset
18+
@Bean
19+
publicTomcatServletWebServerFactorytomcatEmbedded() {
20+
TomcatServletWebServerFactorytomcat =newTomcatServletWebServerFactory();
21+
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer)connector -> {
22+
if ((connector.getProtocolHandler()instanceofAbstractHttp11Protocol<?>)) {
23+
//-1 means unlimited
24+
((AbstractHttp11Protocol<?>)connector.getProtocolHandler()).setMaxSwallowSize(-1);
25+
}
26+
});
27+
returntomcat;
28+
}
29+
30+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
packagecom.neo.controller;
2+
3+
importorg.springframework.web.bind.annotation.ControllerAdvice;
4+
importorg.springframework.web.bind.annotation.ExceptionHandler;
5+
importorg.springframework.web.multipart.MultipartException;
6+
importorg.springframework.web.servlet.mvc.support.RedirectAttributes;
7+
8+
@ControllerAdvice
9+
publicclassGlobalExceptionHandler {
10+
11+
//https://jira.spring.io/browse/SPR-14651
12+
//4.3.5 supports RedirectAttributes redirectAttributes
13+
@ExceptionHandler(MultipartException.class)
14+
publicStringhandleError1(MultipartExceptione,RedirectAttributesredirectAttributes) {
15+
System.out.printf(e.getMessage());
16+
redirectAttributes.addFlashAttribute("message",e.getMessage());
17+
return"redirect:/uploadStatus";
18+
}
19+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
packagecom.neo.controller;
2+
3+
importorg.springframework.stereotype.Controller;
4+
importorg.springframework.web.bind.annotation.GetMapping;
5+
importorg.springframework.web.bind.annotation.PostMapping;
6+
importorg.springframework.web.bind.annotation.RequestParam;
7+
importorg.springframework.web.multipart.MultipartFile;
8+
importorg.springframework.web.servlet.mvc.support.RedirectAttributes;
9+
10+
importjava.io.IOException;
11+
importjava.nio.file.Files;
12+
importjava.nio.file.Path;
13+
importjava.nio.file.Paths;
14+
15+
@Controller
16+
publicclassUploadController {
17+
//Save the uploaded file to this folder
18+
privatestaticStringUPLOADED_FOLDER ="E://temp//";
19+
20+
@GetMapping("/")
21+
publicStringindex() {
22+
return"upload";
23+
}
24+
25+
@PostMapping("/upload")// //new annotation since 4.3
26+
publicStringsingleFileUpload(@RequestParam("file")MultipartFilefile,
27+
RedirectAttributesredirectAttributes) {
28+
if (file.isEmpty()) {
29+
redirectAttributes.addFlashAttribute("message","Please select a file to upload");
30+
return"redirect:uploadStatus";
31+
}
32+
33+
try {
34+
// Get the file and save it somewhere
35+
byte[]bytes =file.getBytes();
36+
Pathdir =Paths.get(UPLOADED_FOLDER);
37+
Pathpath =Paths.get(UPLOADED_FOLDER +file.getOriginalFilename());
38+
// Create parent dir if not exists
39+
if(!Files.exists(dir)) {
40+
Files.createDirectories(dir);
41+
}
42+
Files.write(path,bytes);
43+
redirectAttributes.addFlashAttribute("message",
44+
"You successfully uploaded '" +file.getOriginalFilename() +"'");
45+
46+
}catch (IOExceptione) {
47+
redirectAttributes.addFlashAttribute("message","Server throw IOException");
48+
e.printStackTrace();
49+
}
50+
return"redirect:/uploadStatus";
51+
}
52+
53+
@GetMapping("/uploadStatus")
54+
publicStringuploadStatus() {
55+
return"uploadStatus";
56+
}
57+
58+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
2+
#search multipart
3+
spring.servlet.multipart.max-file-size=10000MB
4+
spring.servlet.multipart.max-request-size=10000MB
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<configuration>
3+
4+
<appendername="STDOUT"class="ch.qos.logback.core.ConsoleAppender">
5+
<layoutclass="ch.qos.logback.classic.PatternLayout">
6+
<Pattern>
7+
%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
8+
</Pattern>
9+
</layout>
10+
</appender>
11+
12+
<loggername="org.springframework.web"level="error"additivity="false">
13+
<appender-refref="STDOUT"/>
14+
</logger>
15+
16+
<loggername="com.neo"level="debug"additivity="false">
17+
<appender-refref="STDOUT"/>
18+
</logger>
19+
20+
<rootlevel="error">
21+
<appender-refref="STDOUT"/>
22+
</root>
23+
24+
</configuration>
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<formid='myupload'action='http://localhost:8080/uploadSign'method='post'enctype='multipart/form-data'>
2+
<divclass="demo">
3+
<divclass="btn">
4+
<span>添加附件</span>
5+
<inputid="fileupload"type="file"name="file1"></div>
6+
<divclass="progress">
7+
<spanclass="bar"></span>
8+
<spanclass="percent">0%</span></div>
9+
<!-- 显示已上传的文件名 -->
10+
<divclass="files"></div>
11+
<!-- 显示已上传的图片-->
12+
<divclass="showimg"></div>
13+
</div>
14+
<inputtype="submit"onclick="gosubmit2()"/></form>
15+
<scriptsrc="https://cdn.bootcss.com/jquery/1.6.4/jquery.js"></script>
16+
<scripttype="text/javascript"src="https://cdn.bootcss.com/jquery.form/4.1.0/jquery.form.min.js"></script>
17+
<scripttype="text/javascript">varbar=$('.bar');//进度条
18+
varpercent=$('.percent');//获取上传百分比
19+
varshowimg=$('.showimg');//显示图片的div
20+
varprogress=$('.progress');//显示进度的div
21+
varfiles=$('.files');//文件上传控件的input元素
22+
varbtn=$('.btn span');//按钮文本
23+
functiongosubmit2(){
24+
$("#myupload").ajaxSubmit({
25+
dataType:'json',
26+
//返回数据类型
27+
beforeSend:function(){
28+
showimg.empty();
29+
progress.show();
30+
varpercentVal='0%';
31+
bar.width(percentVal);
32+
percent.html(percentVal);
33+
btn.html('上传中..');
34+
},
35+
//更新进度条事件处理代码
36+
uploadProgress:function(event,position,total,percentComplete){
37+
varpercentVal=percentComplete+'%';
38+
bar.width(percentVal);
39+
percent.html(percentVal);
40+
},
41+
success:function(data){//图片上传成功时
42+
//获取服务器端返回的文件数据
43+
alert(data.name+","+data.pic+","+data.size);
44+
},
45+
error:function(xhr){
46+
btn.html(上传失败);
47+
bar.width('0');
48+
files.html(xhr.responseText);
49+
}
50+
});
51+
}</script>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<!DOCTYPE html>
2+
<htmlxmlns:th="http://www.thymeleaf.org">
3+
<body>
4+
5+
<h1>Spring Boot file upload example</h1>
6+
7+
<formmethod="POST"action="/upload"enctype="multipart/form-data">
8+
<inputtype="file"name="file"/><br/><br/>
9+
<inputtype="submit"value="Submit"/>
10+
</form>
11+
12+
</body>
13+
</html>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<!DOCTYPE html>
2+
<htmllang="en"xmlns:th="http://www.thymeleaf.org">
3+
<body>
4+
5+
<h1>Spring Boot - Upload Status</h1>
6+
7+
<divth:if="${message}">
8+
<h2th:text="${message}"/>
9+
</div>
10+
11+
</body>
12+
</html>

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp