一、创建上传页面upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
文件:<input type="file" name="file">
姓名:<input type="text" name="name">
<input type="submit" value="提交">
</form>
</body>
</html>
二、创建controller
@RestController
public class UploadController {
//上传到具体的地址
private static final String filePath = "";
@PostMapping(value = "/upload")
public Object upload(MultipartFile file, HttpServletRequest request){
//获取name值
String name = request.getParameter("name");
System.out.println("姓名:" + name);
//获取文件名
String fileName = file.getOriginalFilename();
System.out.println("文件名:" + fileName);
//获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的后缀名为:" + suffixName);
//文件上传后的路径
fileName = UUID.randomUUID() + suffixName;
System.out.println("转换后的名称:" + fileName);
File dest = new File(filePath + fileName);
try{
file.transferTo(dest);
return fileName;
}catch (Exception e){
e.printStackTrace();
}
return "fail";
}
}
三、测试上传
http://localhost:8080/upload.html
四、上传文件大小的配置
在启动类中加入配置方法:
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件最大
factory.setMaxFileSize("10240KB"); //KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize("1024000KB");
return factory.createMultipartConfig();
}
五、服务器一般都是linux系统,当用jar包启动工程时,需要指定磁盘路径
在application.properties文件中加以下配置:
##要上传到的路径
web.upload-path=/usr/local/file/
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path}