1、config包下的操作
1.1、创建MyWebApplicationInit类
如何创建第一个SpringMvc步骤 以配置类的形式代替xml文件(点击链接查看)
1.2、设置文件大小(自定义)
1.3、创建SpringMvcConfig类 并实现 WebMvcConfigurer接口
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
//视图解析器
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver =
new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
//配置WebMvc相关配置,实现接口 WebMvcConfigurer
//静态资源处理
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
//文件解析器
@Bean
public MultipartResolver multipartResolver() {
StandardServletMultipartResolver multipartResolver =
new StandardServletMultipartResolver();
return multipartResolver;
}
}
1.4、创建AppConfig类 @Import注解导入类
@Configuration
@ComponentScan("")//注解扫描如:com.xxx
@Import({SpringMvcConfig.class, SpringConfig.class})
public class AppConfig {
}
1.5、我的config包下面的类
2、Service包下面的操作
2.1、定义接口FileService类
public interface FileService {
public String upload(MultipartFile file, HttpServletRequest request) throws Exception;
}
2.2、创建FileServiceImpl并实现FileService接口
@Service
public class FileServiceImpl implements FileService {
@Override
public String upload(MultipartFile file, HttpServletRequest request) throws Exception {
//文件上传
List<String> allowFile= Arrays.asList("jpg","png","gif","bmp");
//1.获取文件的名
String filename = file.getOriginalFilename();
System.out.println("filename:文件名" + filename);
String suffix = FileUtil.getSuffix(filename);//文件后缀名
// if (!allowFile.contains(suffix)){
// throw new FileUploadException("文件格式错误");
// }
System.out.println("suffix:文件后缀" + suffix);
byte[] bytes = file.getBytes();//文件大小
System.out.println("bytes:文件大小" + bytes.length);
//2.上传路径
String path = request.getServletContext().getRealPath("/upload");
FileUtil.writeBytes(bytes, path + "/" + filename);
File dir = FileUtil.mkdir(path);
if (!dir.exists()) {
dir.mkdir();//创建文件夹
}
//3.拼接真实文件
String uuid = IdUtil.randomUUID();
File uploadFile = new File(path + "/" + uuid + "." + suffix);
//上传文件
file.transferTo(uploadFile);
return uuid+"."+suffix;
}
}
2.3、我的Service包
3、文件上传操作
3.1、创建xxx.jsp
注意要导入jquery
<script src="${pageContext.request.contextPath}/static/js/jquery.js"></script>>
<form id="userForm" action="${pageContext.request.contextPath}/user/add" method="post" enctype="multipart/form-data">
姓名<input type="text" name="username"/><br>
<input type="text" id="avatar" name="avatar"/>
头像<input type="file" id="file" name="file"/><br>
预览 <div id="yulan"></div><br>
<input type="submit" value="上传"/>
</form>
3.2、发送ajax请求
$("#file").change(function () {
let url = '${pageContext.request.contextPath}/upload';
//发送ajax请求
$.ajax({
url: url,
type: "post",//必须是post
data: new FormData($("#userForm")[0]),//带有 enctype="multipart/form-data"
processData: false,//告诉JQuery不要去处理发送的数据
contentType: false,//告诉JQuery不要去处理发送的数据
success: function (res) {
$("#avatar").val(res);
//获取文件上传的图片并且展示
let img=$("<img src='${pageContext.request.contextPath}/upload/"+res+"'>")
$("#yulan").empty().append(img)
},
error: function () {
alert("上传失败")
}
})
})
3.3、控制层接收请求
@RequestMapping(value = "/add",produces="application/json;charset=utf-8")
public String add(SysUser sysUser) {
System.out.println(sysUser.getUsername());
System.out.println(sysUser.getAvatar());
return "index";
}
@RequiredArgsConstructor
@RestController
public class FilerController {
private final FileService fileService;
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
System.out.println("upload.class");
System.out.println(file);
return fileService.upload(file, request);
}
}
3.4我的包
4、效果图
5、需要导入的jar包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.1.11</version>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.27</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.27</version>
</dependency>
</dependencies>
标签:String,SpringMvc,upload,System,Ajax,file,println,上传,public
From: https://blog.csdn.net/or77iu_N/article/details/141634893