因为项目中用到多处图片上传功能,所以自己整理一个比较简单的SpringMVC图片上传的公共类,方便调用:
页面调用时需要注意:
1、所在的form标签需要加入enctype="multipart/form-data"属性
2、<input type="file" id="fileImageFile" name="fileImageFile" >
名字必须定义成 file + 属性名称 (属性名称用于后台get/set 映射保存修改)
接口:
public interface UploadDemoService<T> {
/**
*
* @Title: uploadForm
* @Description: 实现图片上传服务器
* @param request
* @param entityClass
* 保存图片路径的实体类(如:layoutInfo.class)
* @param entity
* 表单提交保存的实体对象
* @param path
* 图片路径(如果整个系统只有一个图片地址可以不用加这个参数,直接写到公共方法中)
* @return
* @throws Exception
* @return T
* @throws
*/
public String uploadForm(HttpServletRequest request, Class<T> entityClass, T entity, String uploadPath) throws Exception;
}
实现类:
import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.lanyoung.stone.modules.cp.Constants;
@Service
public class UploadDemoServiceImpl<T> implements UploadDemoService<T> {
private static final Logger log = LoggerFactory.getLogger(UploadDemoServiceImpl.class);
// 存储文件格式
private static final HashMap<String, String> TypeMap = new HashMap<String, String>();
static {
TypeMap.put("image", "gif,jpg,jpeg,png,bmp,ico");
}
@Override
public String uploadForm(HttpServletRequest request, Class<T> entityClass, T entity, String uploadPath) throws Exception {
// 路径必须最后是“/”
if (uploadPath != null && uploadPath.length() > 0 && !uploadPath.substring(uploadPath.length() - 1).equals("/")) {
uploadPath = uploadPath + "/";
}
CommonsMultipartResolver cmr = new CommonsMultipartResolver( request.getServletContext());
if (cmr.isMultipart(request)) {
// 检查上传文件的目录
File uploadDir = new File(uploadPath);
// 如果文件夹不存在则创建
if (!uploadDir.exists() && !uploadDir.isDirectory()) {
log.info("//文件夹不存在,创建中....");
uploadDir.mkdirs();
} else {
log.info("//目录存在");
}
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
Iterator<String> files = mRequest.getFileNames();
// 获取图片信息
while (files.hasNext()) {
MultipartFile mFile = mRequest.getFile(files.next());
// 获得属性名称
String attributeName = mFile.getName().substring(4);
attributeName = attributeName.substring(0, 1).toLowerCase() + attributeName.substring(1);
// 判断文件是否存在
if (mFile != null && !mFile.isEmpty()) {
String imageName = mFile.getOriginalFilename();
// 判断图片名称是否正确
String fileSuffix = imageName.substring(
imageName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.asList(TypeMap.get("image").split(",")).contains(fileSuffix)) {
log.info(mFile.getName() + "中上传的文件格式不正确");
return "上传的文件格式不正确";
}
// 判断文件上传大小
if (mFile.getSize() > Constants.file_size) {
log.info(mFile.getName() + "中文件超过上传大小");
return "文件超过上传大小";
}
// 获得当前时间的毫秒数
Date dt = new Date();
Long time = dt.getTime();
// 图片名称(毫秒数+随机数)
String fileName = time.toString()+ Math.round(Math.random() * 10000000) + "."+ fileSuffix;
// 图片存放的路径
String path = uploadPath + fileName;
log.info("path=" + path);
File localFile = new File(path);
mFile.transferTo(localFile);
// 获得实体类中对应的get方法
PropertyDescriptor pd = new PropertyDescriptor(attributeName, entityClass);
Method getMethod = pd.getReadMethod();// 获得get方法
Object imagePathObject = getMethod.invoke(entity);
// 判断实体类中该属性是否为空,不为空删除
if (imagePathObject != null && !imagePathObject.equals("")) {
String imagePath = (String) imagePathObject;
// 获得图片
File file = new File(imagePath);
if (file.exists()) {
file.delete();
log.info("删除路径:" + imagePath);
}
}
// 给实体类中对应的set方法赋值
Class<?> paramClass = entityClass.getDeclaredField(attributeName).getType();
// 拼装set方法名称
String methodName = "set"+ attributeName.substring(0, 1).toUpperCase()+ attributeName.substring(1);
// 根据名称获取方法
Method method = entityClass.getMethod(methodName, paramClass);
// 调用invoke执行赋值
method.invoke(entity, path);
}
}
}
return "success";
}
}
controller内调用:
//参数必须是接收上传图片属性的实体类
@Autowired
private UploadDemoService<CompanyBaseDetail> uploadDemoService;
// 上传图片后保存的路径(绝对和相对都可以,如果整个系统只需要将图片保存到一个文件夹,可以把路径写在公共类中)
String uploadPath = "/data/image/company";
uploadDemoService.uploadForm(request, CompanyBaseDetail.class, detail, uploadPath);