一、在springBoot项目中的pom.xml添加依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
二、在资源目录下的static目录下中创建一个upload.html的表单文件:
文件的内容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片上传页面</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" value="请选择文件">
<input type="submit" value="上传">
</form>
</body>
</html>
接口是/upload,请求方式是post
三、创建文件上传处理接口:
package org.sang.cc;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
@PostMapping("/upload")
public String upload(MultipartFile uploadFile,HttpServletRequest req)
{
try {
//String realPath=req.getSession().getServletContext().getRealPath("/");
String realPath=ResourceUtils.getURL("classpath:").getPath();
String format=sdf.format(new Date());
System.out.println("realPath:"+realPath+"static/"+format);
File folder=new File(realPath+"static/"+format);
if(!folder.isDirectory())
{
folder.mkdirs();
}
String oldName=uploadFile.getOriginalFilename();
String newName=UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
uploadFile.transferTo(new File(folder,newName));
String filePath=req.getScheme()+"://"+req.getServerName()+":"+
req.getServerPort()+"/static/"+format+"/"+newName;
return filePath;
}catch(IOException e)
{
e.printStackTrace();
}
return "上传失败!";
}
}
将上传的文件存储在static目录下,返回一个路径字符串
四、上传文件配置:
配置application.properties文件内容
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.location=E:\\temp
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=false
- 配置上传文件的临时保存位置为E:\temp
- 配置单文件最大上传大小为1MB
- 多文件时总大小为10MB
五、测试:
上传页
上传完成页
展示图片页
物理保存目录