最近在做springboot项目的时候,需要上传图片并且提供URL给前端。废话不多说,直接上代码。
首先在application.yml配置中添加如下配置
###服务启动端口号
server:
port: 8003
tomcat:
uri-encoding: UTF-8
###文件上传
file:
###静态资源对外暴露的访问路径
staticAccessPath: /api/file/**
###静态资源实际存储路径
uploadFolder: F:/upload/mall/
uploadImage: image/
###项目名
servlet:
context-path:
###文件上传
multipart:
enabled: true
max-file-size: 10mb
max-request-size: 10mb
###服务名称(服务注册到eureka名称)
spring:
application:
name: test
mvc:
throw-exception-if-no-handler-found: true
static-path-pattern: /**
#静态资源访问
resources:
add-mappings: true
static-locations: classpath\:/META-INF/resources/,classpath\:/resources/,classpath\:/static/,classpath\:/public/,file\:${file.uploadFolder}${file.uploadImage}
http:
encoding:
force: true
charset: utf-8
enabled: true
然后新建一个类,继承WebMvcConfigurerAdapter
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SuppressWarnings("deprecation")
@Configuration
public class UploadFilePathConfig extends WebMvcConfigurerAdapter{
@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${file.uploadFolder}")
private String uploadFolder;
@Value("${file.uploadImage}")
private String uploadImage;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations("file:///" + uploadFolder + uploadImage);
super.addResourceHandlers(registry);
}
}
接着编写controller类
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.snimay.entity.RetStruct;
import com.snimay.utils.FileUpload;
import com.snimay.utils.exception.MallException;
import com.snimay.utils.map.MapUtil;
@Controller
@RequestMapping("/fileupload/")
public class FileUploadController {
//获取主机端口
@Value("${server.port}")
private String POST;
//静态资源对外暴露的访问路径
@Value("${file.staticAccessPath}")
private String staticAccessPath;
//实际存储路径
@Value("${file.uploadFolder}")
private String uploadFolder;
//图片
@Value("${file.uploadImage}")
private String uploadImage;
/**
* 获取所有文件上传前缀路径
*
* @param file
* @param request
* @return
*/
@ResponseBody
@RequestMapping(value = "getSourceUrl.do", produces = "text/html;charset=UTF-8")
public String getPrefixPath(HttpServletRequest request, HttpServletResponse response) {
JSONObject resultObj = new JSONObject();
JSONObject dataObj = new JSONObject();
String fileUploadBackUrl = FileUpload.fileUploadBackUrl;
dataObj.put("sourceUrl", fileUploadBackUrl + FileUpload.sourceDir);
resultObj.put("code", 0);
resultObj.put("msg", "获取所有路径成功");
resultObj.put("data", dataObj);
return resultObj.toString();
}
/**
* Description: 上传名片图片
*
* @param request
* @param response
* @return
*/
@SuppressWarnings("unchecked")
@ResponseBody
@RequestMapping(value = "uploadBusinessCardImage.do", produces = "text/html;charset=UTF-8")
public String uploadBusinessCardImage(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
throw new MallException(-1,"上传文件为空");
}
String originalFilename = file.getOriginalFilename();
String result = FileUpload.FileUpLoadAndGetParam(file, POST, staticAccessPath, uploadFolder, uploadImage, originalFilename);
Map resultMap = JSONObject.parseObject(result.trim());
Map layeditMap = new HashMap<>();
if (resultMap.get("code").equals(0)) {
Map resultDataMap = (Map) resultMap.get("data");System.out.println(resultDataMap);
layeditMap.put("src", resultDataMap.get("http_url"));
layeditMap.put("title", resultDataMap.get("file_name"));
resultMap.put("data", layeditMap);
resultMap.remove("param");
result = resultMap.toString();
}
return result;
} catch (Exception e) {
return new RetStruct(-1, e.getMessage()).toString();
}
}
}
上传文件的工具类,最后返回结果封装为json格式
public class FileUpload {
private static final Logger log = LoggerFactory.getLogger(FileUpload.class);
public static String FILES_TYPE;
public static String IMG_TYPE;
public static int UPLOAD_MAX_SIZE;
public static long UPLOAD_MAX_SIZE_BYTE;
private Map params;
private Map mFilesUrlJSON = new HashMap<>();
private static long fileSize = 0;
private String errStr = "";
static {
InputStream is = null;
try {
Properties pro = new Properties();
is = FileUpload.class.getResourceAsStream("/config.properties");
pro.load(is);
FILES_TYPE = FileType.getAllName();
IMG_TYPE = ImgType.getAllName();
UPLOAD_MAX_SIZE = pro.getProperty("uploadMaxSize") == null ? 2
: Integer.parseInt(pro.getProperty("uploadMaxSize"));
UPLOAD_MAX_SIZE_BYTE = UPLOAD_MAX_SIZE * 1024 * 1024;
is.close();
} catch (IOException e) {
ILogUtil.info(e.getMessage());
if (is != null) {
try {
is.close();
} catch (IOException e1) {
ILogUtil.info("关闭流出错.");
}
}
}
}
/**
* Description:
* @param file 文件对象
* @param POST 端口号
* @param staticAccessPath 对外显示路径
* @param uploadFolder 上传文件夹的主路径
* @param filePath 上传文件的文件夹路径
* @param originalFilename 原始文件名称
* @return
*/
public static String FileUpLoadAndGetParam(MultipartFile file, String POST, String staticAccessPath,
String uploadFolder, String filePath, String originalFilename) {
FileUpload fu = new FileUpload();
if (!fu.writeFile(file, POST, staticAccessPath, uploadFolder, filePath, originalFilename)) {
return RetResponse(10, "写文件失败," + fu.getErrStr());
}
JSONObject obj = fu.getFilesUrlJson();
JSONObject json = new JSONObject();
json.put("code", 0);
json.put("msg", "上传成功");
json.put("data", obj);
json.put("param", fu.getParamsJson());
return json.toString();
}
private boolean writeFile(MultipartFile file, String POST, String staticAccessPath,
String uploadFolder,String filePath, String originalFilename) {
fileSize = file.getSize();
File fileExists = new File(uploadFolder + filePath);
try {
if (!fileExists.exists()) {
fileExists.mkdirs();
}
} catch (Exception e) {
ILogUtil.info(e.getMessage());
return false;
}
String oldFileName = originalFilename;
if (!checkFile(oldFileName, FILES_TYPE)) {
errStr = "校验文件类型失败,系统支持格式:" + FILES_TYPE;
ILogUtil.info("校验文件类型失败");
return false;
}
// 不是所有的上传文件都有扩展名,需要允许上传的文件没有扩展名
String suffix = "";
int index = oldFileName.lastIndexOf(".");
if (index != -1) {
suffix = oldFileName.substring(index);
}
// 生成随机名称
String fileName = UUIDUtils.getUUID(16) + suffix;
mFilesUrlJSON.put("http_url", saveUploadFileVirtualUrl(POST, staticAccessPath) + fileName);
mFilesUrlJSON.put("file_name", fileName);
mFilesUrlJSON.put("server_url", saveUploadFileVirtualUrl(POST, staticAccessPath));
mFilesUrlJSON.put("path", "/" + filePath + fileName);// 存储的目录
mFilesUrlJSON.put("file_size", fileSize);
mFilesUrlJSON.put("suffix", suffix);
mFilesUrlJSON.put("old_file_name", oldFileName);
File newFile = new File(uploadFolder + filePath, fileName);
try {
file.transferTo(newFile);
} catch (Exception e) {
errStr = e.getMessage();
ILogUtil.info(e.getMessage());
return false;
}
return true;
}
/**
* Description: 获取服务器地址,拼接虚拟路径
* @return
*/
private String saveUploadFileVirtualUrl(String POST, String staticAccessPath) {
//获取本机IP
String host = null;
try {
host = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
ILogUtil.error("get server host Exception e:", e);
}
String virtual_url = host + ":" + POST + staticAccessPath.substring(0, staticAccessPath.length()-2);
return virtual_url;
}
private boolean checkFile(String fileName, String filesType) {
// 获取文件后缀
if (filesType == null) {
// 不校验
return true;
}
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
if (filesType.contains(suffix.trim().toLowerCase())) {
return true;
}
return false;
}
private Object getParamsJson() {
return (JSONObject) JSONObject.toJSON(params);
}
private JSONObject getFilesUrlJson() {
return JSONObject.parseObject(JSON.toJSONString(mFilesUrlJSON));
}
private String getErrStr() {
return errStr;
}
public static String RetResponse(int code, String msg) {
JSONObject obj = new JSONObject();
obj.put("code", code);
obj.put("msg", msg);
return obj.toString();
}
}
最后是生成随机数的工具类
import java.util.UUID;
public class UUIDUtils {
public static String getUUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
public static String getUUID(Integer len) {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
}
}
用postman进行测试