Springboot官网在这里:https://spring.io/guides/gs/uploading-files/
需要使用的jar包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
form表单发送请求存储图片
<form action="http://localhost:8080/file/fileUpload" method="post" enctype="multipart/form-data">
<label>上传图片</label>
<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
文件上传,必须使用enctype="multipart/form-data"
,定义多部件的媒体文件
application.properties添加固定存储路径。以及文件访问路径格式
filepath=D:……/src/main/resources/static/images/
然后是controller代码
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${filepath}")
private String path;
@PostMapping(value = "/fileUpload")
public String fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request) {
if (file.isEmpty()) {
System.out.println("文件为空");
}
String fileName = file.getOriginalFilename(); // 文件名
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
String filePath = path; // 上传后的路径
fileName = UUID.randomUUID() + suffixName; // 新文件名
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
String filename = path + fileName;
model.addAttribute("filename", filename);
String requestURL = request.getRequestURL().toString();
String requestURI = request.getRequestURI();
System.out.println("requestURL"+requestURL);
System.out.println("requestURI"+requestURI);
return filename;
}
}
添加资源映射路径
@Value("${filepath}")
private String path;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations(path);
}
}
映射是必须的,他是主机地址和网络地址相互转换的关键。
更新
上面直接给出绝对路径只能在本机运行,换一台机子,就会找不到这个路径,
更新使用动态获取当前运行路径,并放在项目目录/static/images文件下
- 添加一个工具类,用来获取当前工作路径.调用此方法,获取运行时路径
import org.springframework.util.ResourceUtils;
import java.io.FileNotFoundException;
public class GetPath {
static public String getPath() throws FileNotFoundException {
return ResourceUtils.getURL("src/main/resources/static/images").getPath();
}
- 在
FileController
和映射配置获取此path
String filePath = GetPath.getPath();
注:此方法会抛出异常,使用时捕捉或抛出都可