1.读取配置文件的工具类 GetPathUtil
package com.yl.utils;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class GetPathUtil {
public Map<String,String> readRcErpURL(){
try{
String url = this.getClass().getResource("").getPath().replaceAll("%20", " ");
String path = url.substring(0, url.indexOf("WEB-INF")) + "WEB-INF/pathConfig.properties";
Properties config = new Properties();
config.load(new FileInputStream(path));
Map map = new HashMap<>();
//这里是要获取的变量 存放在map中 方便取值map.put("ueditorPath",config.getProperty("ueditorPath"));
map.put("uploadFilePath",config.getProperty("uploadFilePath"));
map.put("uploadImgsPath",config.getProperty("uploadImgsPath"));
return map;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
2.编写配置文件 pathConfig.properties
#文件上传配置
#1.文件上传路径
uploadFilePath = /opt/upload/file/
#2.图片上传路径
uploadImgsPath = /opt/upload/imgs/
#3.百度富文本路径
ueditorPath = /opt/upload/file/
3.在场景中使用
@RequestMapping(value = {"/uploadPng"}, method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public AjaxResult uploadPng(HttpServletRequest request) throws IllegalStateException, IOException {
//-------------useStart----------
GetPathUtil getPathUtil = new GetPathUtil();
Map<String, String> pathMap = getPathUtil.readRcErpURL();
String uploadImgsPath = pathMap.get("uploadImgsPath");
//-------------useEnd----------
String name = GenerateID.getIdByUUID();
String newFileName = "";
String realPath = uploadImgsPath;
File filePath = new File(realPath);
if (!filePath.exists()) {
filePath.mkdirs();// 创建文件根目录
}
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile(iter.next().toString());
if (file != null) {
String extensionName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
newFileName = String.valueOf(name) + "." + extensionName;
String path = String.valueOf(realPath) + newFileName;
file.transferTo(new File(path));
}
}
}
AjaxResult ar = new AjaxResult();
ar.setInfo(request.getContextPath() + "/uploadImgs/" + newFileName);
ar.setStatusCode(Integer.valueOf(1));
ar.setMessage("操作成功");
return ar;
}