当前位置:网站首页>16. File upload
16. File upload
2022-08-10 23:49:00 【If you want to learn, learn Big Wolf】
文章目录
16.1 应用实例
16.1.1 需求说明
- 演示 Spring-Boot Register users through the form,And support uploading pictures
- 回顾 SpringMVC 文件上传 ==> 文章链接
16.1.2 代码实现
- 创建 templates/upload.html,Only one avatar is required,And pets can upload multiple pictures
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>upload</title>
</head>
<body bgcolor="#CED3FE">
<img src="images/1.GIF"/>
<hr/>
<div style="text-align: center">
<h1>注册用户~</h1>
<form action="#" method="post" th:action="@{/upload}" enctype="multipart/form-data">
用户名:<input type="text" style="width:150px" name="name"/><br/><br/>
电 邮:<input type="text" style="width:150px" name="email"/><br/><br/>
年 龄:<input type="text" style="width:150px" name="age"/><br/><br/>
职 位:<input type="text" style="width:150px" name="job"/><br/><br/>
头 像:<input type="file" style="width:150px" name="header"><br/><br/>
宠 物:<input type="file" style="width:150px" name="photos" multiple><br/><br/>
<input type="submit" value="注册"/>
<input type="reset" value="重新填写"/>
</form>
</div>
<hr/>
<!--<img src="images/logo.png"/>-->
</body>
</html>
- 创建 D:\xjs_springboot\springboot-usersys\src\main\java\com\xjs\springboot\controller\UploadController.java
package com.xjs.springboot.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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: 谢家升 * @Version: 1.0 */
@Controller
@Slf4j
public class UploadController {
//Processing is forwarded to user registration-Complete the file upload page
@GetMapping("/upload.html")
public String uploadPage() {
return "upload"; //thymeleaf 视图解析,转发到 templates/upload.html
}
//处理用户的注册请求-Including handling file uploads
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("name") String name,
@RequestParam("email") String email,
@RequestParam("age") Integer age,
@RequestParam("job") String job,
@RequestParam("header") MultipartFile header,
@RequestParam("photos") MultipartFile[] photos) throws IOException {
//Output the obtained information
log.info("上传的信息 name={} email={} age={} job={} header={} photos={}",
name, email, age, job, header.getSize(), photos.length);
//We save the file to the specified directory,比如 D:\\temp_upload
//1. Save the file to the specified directory first 比如 D:\\temp_upload
if (!header.isEmpty()) {
//处理头像
//Get the original filename of the uploaded file
String originalFilename = header.getOriginalFilename();
header.transferTo(new File("D:\\temp_upload\\" + originalFilename));
}
//Process pet pictures
if (photos.length > 0) {
for (MultipartFile photo : photos) {
//遍历
if (!photo.isEmpty()) {
String originalFilename = photo.getOriginalFilename();
photo.transferTo(new File("D:\\temp_upload\\" + originalFilename));
}
}
}
//==============================================
//2. I'll demonstrate saving the file to a dynamically created directory later
// 比如:类路径下的
//(1) Get the classpath first(运行的时候)
String path = ResourceUtils.getURL("classpath:").getPath();
//log.info("path={}", path);
//(2)Dynamically create the specified directory
File file = new File(path + "static/images/upload/");
if (!file.exists()) {
//如果目录不存在 就创建
file.mkdirs();
}
//处理头像
if (!header.isEmpty()) {
String originalFilename = header.getOriginalFilename();
//Here you need to specify the absolute path to save the file,即:
//log.info("保存文件的绝对路径={}", file.getAbsolutePath());
// The output can see whether it needs to be added when the path is spliced "/"
//Save to a dynamically created directory
header.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
}
//Process pet pictures
if (photos.length > 0) {
for (MultipartFile photo : photos) {
String originalFilename = photo.getOriginalFilename();
//Save to a dynamically created directory
photo.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
}
}
return "注册用户成功/文件上传成功";
}
}
- 修改 WebConfig 配置,放行/upload.html 和 /upload 请求
package com.xjs.springboot.config;
import com.xjs.springboot.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** * @Author: 谢家升 * @Version: 1.0 */
@Configuration
public class WebConfig /*implements WebMvcConfigurer*/ {
//@Override
//public void addInterceptors(InterceptorRegistry registry) {
//
// //注册自定义拦截器LoginInterceptor
// registry.addInterceptor(new LoginInterceptor())
// .addPathPatterns("/**") //这里拦截所有的请求
// .excludePathPatterns("/","/login","/images/**"); //Specifies which to release,Add release request paths according to business needs
//
//}
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截器
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/", "/login", "/images/**", "/upload.html", "/upload");
}
};
}
}
- Modify the parameters of file upload according to project requirements,Otherwise the file upload will throw an exception
创建 resources\application.yml Modify file upload configuration parameters
①
max-file-size
单个文件大小
②max-request-size
一次请求最大上传大小 (多个文件)
spring:
servlet:
multipart:
max-file-size: 10MB # Indicates the maximum upload of a single file 10MB
max-request-size: 50MB # Indicates that multiple files can be uploaded at most in one request 10MB
16.1.3 Complete registered user/上传图片 -测试
16.1.3.1 启动项目
16.1.3.2 浏览器:http://localhost:8080/upload.html
16.1.3.3 页面效果
16.1.4 课后作业-扩展要求
- Fix file overwrite issue,如果文件名相同,There will be coverage issues,如何解决?
- Solve the problem of file sub-directory storage,如果将文件都上传到一个目录下,当上传文件很多时,会造成访问文件速度变慢,因此 可以将文件上传到不同目录 比如 一天上传的文件,Put them together in one folder 年/月/日,比如 2022/11/11 目录
- Refer to the previous study java web ==> 文章链接
16.1.5 homework answers
- Generate a uniquely identified file name
String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
- 修改 UploadController.java
package com.xjs.springboot.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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;
import java.util.UUID;
/** * @Author: 谢家升 * @Version: 1.0 */
@Controller
@Slf4j
public class UploadController {
//Processing is forwarded to user registration-Complete the file upload page
@GetMapping("/upload.html")
public String uploadPage() {
return "upload"; //thymeleaf 视图解析,转发到 templates/upload.html
}
//处理用户的注册请求-Including handling file uploads
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("name") String name,
@RequestParam("email") String email,
@RequestParam("age") Integer age,
@RequestParam("job") String job,
@RequestParam("header") MultipartFile header,
@RequestParam("photos") MultipartFile[] photos) throws IOException {
//Output the obtained information
log.info("上传的信息 name={} email={} age={} job={} header={} photos={}",
name, email, age, job, header.getSize(), photos.length);
//We save the file to the specified directory,比如 D:\\temp_upload
//1. Save the file to the specified directory first 比如 D:\\temp_upload
//if (!header.isEmpty()) { //处理头像
// //Get the original filename of the uploaded file
// String originalFilename = header.getOriginalFilename();
// header.transferTo(new File("D:\\temp_upload\\" + originalFilename));
//}
//Process pet pictures
//if (photos.length > 0) {
// for (MultipartFile photo : photos) { //遍历
// if (!photo.isEmpty()) {
// String originalFilename = photo.getOriginalFilename();
// photo.transferTo(new File("D:\\temp_upload\\" + originalFilename));
// }
// }
//}
//==============================================
//2. I'll demonstrate saving the file to a dynamically created directory later
// 比如:类路径下的
//(1) Get the classpath first(运行的时候)
String path = ResourceUtils.getURL("classpath:").getPath();
//log.info("path={}", path);
//(2)Dynamically create the specified directory
File file = new File(path + "static/images/upload/");
if (!file.exists()) {
//如果目录不存在 就创建
file.mkdirs();
}
//处理头像
if (!header.isEmpty()) {
String originalFilename = header.getOriginalFilename();
String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
//Here you need to specify the absolute path to save the file,即:
//log.info("保存文件的绝对路径={}", file.getAbsolutePath());
// The output can see whether it needs to be added when the path is spliced "/"
//Save to a dynamically created directory
//header.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
header.transferTo(new File(file.getAbsoluteFile() + "/" + fileName));
}
//Process pet pictures
if (photos.length > 0) {
for (MultipartFile photo : photos) {
String originalFilename = photo.getOriginalFilename();
String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
//Save to a dynamically created directory
//photo.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
photo.transferTo(new File(file.getAbsoluteFile() + "/" + fileName));
}
}
return "注册用户成功/文件上传成功";
}
}
- 编写一个工具类,The corresponding directory can be generated according to the current date
- 编写工具类 WebUtils.java
package com.xjs.springboot.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
/** * @Author: 谢家升 * @Version: 1.0 */
public class WebUtils {
//Define a file upload path
public static String UPLOAD_FILE_DIRECTORY = "static/images/upload/";
//编写方法, Generate a directory based on the current date 年/月/日
public static String getUploadFileDirectory() {
return UPLOAD_FILE_DIRECTORY + new SimpleDateFormat("yyyy/MM/dd").format(new Date());
}
//测试
public static void main(String[] args) {
System.out.println(WebUtils.getUploadFileDirectory());
}
}
- 修改 UploadController.java
package com.xjs.springboot.controller;
import com.xjs.springboot.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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;
import java.util.UUID;
/** * @Author: 谢家升 * @Version: 1.0 */
@Controller
@Slf4j
public class UploadController {
//Processing is forwarded to user registration-Complete the file upload page
@GetMapping("/upload.html")
public String uploadPage() {
return "upload"; //thymeleaf 视图解析,转发到 templates/upload.html
}
//处理用户的注册请求-Including handling file uploads
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("name") String name,
@RequestParam("email") String email,
@RequestParam("age") Integer age,
@RequestParam("job") String job,
@RequestParam("header") MultipartFile header,
@RequestParam("photos") MultipartFile[] photos) throws IOException {
//Output the obtained information
log.info("上传的信息 name={} email={} age={} job={} header={} photos={}",
name, email, age, job, header.getSize(), photos.length);
//We save the file to the specified directory,比如 D:\\temp_upload
//1. Save the file to the specified directory first 比如 D:\\temp_upload
//if (!header.isEmpty()) { //处理头像
// //Get the original filename of the uploaded file
// String originalFilename = header.getOriginalFilename();
// header.transferTo(new File("D:\\temp_upload\\" + originalFilename));
//}
//Process pet pictures
//if (photos.length > 0) {
// for (MultipartFile photo : photos) { //遍历
// if (!photo.isEmpty()) {
// String originalFilename = photo.getOriginalFilename();
// photo.transferTo(new File("D:\\temp_upload\\" + originalFilename));
// }
// }
//}
//==============================================
//2. I'll demonstrate saving the file to a dynamically created directory later
// 比如:类路径下的
//(1) Get the classpath first(运行的时候)
String path = ResourceUtils.getURL("classpath:").getPath();
//log.info("path={}", path);
//(2)Dynamically create the specified directory
File file = new File(path + WebUtils.getUploadFileDirectory());
if (!file.exists()) {
//如果目录不存在 就创建
file.mkdirs();
}
//处理头像
if (!header.isEmpty()) {
String originalFilename = header.getOriginalFilename();
String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
//Here you need to specify the absolute path to save the file,即:
//log.info("保存文件的绝对路径={}", file.getAbsolutePath());
// The output can see whether it needs to be added when the path is spliced "/"
//Save to a dynamically created directory
//header.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
header.transferTo(new File(file.getAbsoluteFile() + "/" + fileName));
}
//Process pet pictures
if (photos.length > 0) {
for (MultipartFile photo : photos) {
String originalFilename = photo.getOriginalFilename();
String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
//Save to a dynamically created directory
//photo.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
photo.transferTo(new File(file.getAbsoluteFile() + "/" + fileName));
}
}
return "注册用户成功/文件上传成功";
}
}
边栏推荐
猜你喜欢
iNFTnews | In the Web3 era, users will have data autonomy
11. Custom Converter
电脑桌面删除的文件回收站没有,电脑上桌面删除文件在回收站找不到怎么办
9. Rest style request processing
Talk预告 | 中国科学技术大学和微软亚洲研究院联合培养博士生冷燚冲:语音识别的快速纠错模型FastCorrect
进程和线程
【C语言篇】表达式求值(隐式类型转换,算术转换)
Excel English automatic translation into Chinese tutorial
promise详解
[C language] Implementation of guessing number game
随机推荐
SQL注入基础---order by \ limit \ 宽字节注入
The Missing Semester of Your CS Education
【C语言篇】表达式求值(隐式类型转换,算术转换)
鲜花线上销售管理系统的设计与实现
C3604环保黄铜带
Three-column layout implementation
三栏布局实现
SQL注入基础
进程和线程
【C语言】数据储存详解
DASCTF 2022 7月赋能赛 writeup
How to recover data from accidentally deleted U disk, how to recover deleted data from U disk
call,apply,bind指定函数的this指向详解,功能细节,严格和非严格模式下设定this指向
如何快速把握行业机会,更高效地推陈出新,是一个重要的命题
基于SSM实现手机销售商城系统
Google Chrome73~81版本浏览器的跨域问题解决方案
Excel English automatic translation into Chinese tutorial
Kubernetes 计算CPU 使用率
sqlmap结合dnslog快速注入
部分准备金银行已经过时