SpringBoot上传图片到本地并实现URL预览
0.预期效果
项目上传的图片保存到本地磁盘上,返回给前端一个地址,前端根据该地址可以在浏览器上访问查看该图片(感觉和上传到服务器上没啥区别)
1.创建项目
创建个SpringBoot项目,勾选Web依赖,其它看着选选就行。
2.配置YML
配置如下:
server:
port: 8080
servlet:
# 项目路径
context-path: /byb
spring:
application:
# 项目名称
name: UploadImageApplication
servlet:
multipart:
# 单文件大小限制
max-file-size: 10MB
# 总上传大小限制
max-request-size: 10MB
upload:
# 上传的图片保存路径(可自定义)
path: E://upload//avatar//
3.上传Controller
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Slf4j
@RestController
@RequestMapping("/image")
public class ImageUploadController {
@Value(value = "${upload.path}")
private String uploadPath;
/**
* 上传图片并预览
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadImage(@RequestParam(value = "file") MultipartFile multipartFile) {
try {
if (multipartFile.isEmpty()) {
return "文件为空,请重新选择!";
}
// 上传的图片全部保存在 "E://upload//avatar//" 目录下
File file = new File(uploadPath);
if (!file.exists()) {
// 创建完整的目录
file.mkdirs();
}
// 获取文件原始名(包含后缀名)
String orgName = multipartFile.getOriginalFilename();
// 获取文件名(不包括后缀)
String prefixName = orgName.substring(0, orgName.lastIndexOf("."));
// 获取文件后缀名
String suffixName = orgName.substring(orgName.lastIndexOf("."));
// 这是处理后的新文件名
String fileName;
if(orgName.contains(".")) {
// 示例:avatar.123.png,经过处理后得到:avatar.123_1661136943533.png
fileName = prefixName + "_" + System.currentTimeMillis() + suffixName;
} else {
// 上传的图片没有后缀(这压根就不算是一个正常的图片吧?)
return "上传图片格式错误,请重新选择!";
}
String savePath = file.getPath() + File.separator + fileName;
File saveFile = new File(savePath);
// 将上传的文件复制到指定目录
FileCopyUtils.copy(multipartFile.getBytes(), saveFile);
// 返回给前端的图片保存路径;前台可以根据返回的路径拼接完整地址,即可在浏览器上预览该图片
String path = "upload/avatar" + File.separator + fileName;
if (path.contains("\\")) {
path = path.replace("\\", "/");
}
return path;
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return "";
}
}
4.配置WebMvcConfigurer
这个类主要配置资源映射路径;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
/**
* 静态资源的配置 - 使得可以从磁盘中读取 Html、图片、视频、音频等
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/*
配置server虚拟路径,handler为前台访问的URL目录,locations为files相对应的本地路径
也就是说如果有一个 upload/avatar/aaa.png 请求,那程序会到后面的目录里面找aaa.png文件
另外:如果项目中有使用Shiro,则还需要在Shiro里面配置过滤下
*/
registry.addResourceHandler("/upload/avatar/**").addResourceLocations("file:E:\\upload\\avatar\\");
}
}
5.测试上传
- 使用Postman或者Apifox,这里以Apifox为例:启动项目,配置好后点击发送即可
- 返回的地址如下:
- 浏览器上拼接出完整地址即可预览图片
6.总结
总体来说不太麻烦,如果创建个虚拟机,稍微改改还可以上传到虚拟机里面。就酱!