public void addPic(@RequestParam(value = "pic", required = false)MultipartFile pic) throws IOException {
if (pic != null) {
if (FileUtil.isAllowUpImg(pic.getOriginalFilename())) {
InputStream stream=null;
try {
stream=pic.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
String subFolder = "adv";//路径中添加的一个字符串
String fileName=pic.getOriginalFilename();
if(stream==null){
throw new IllegalArgumentException("file or filename object is null");
}
/**
* 判断图片是否允许的类型
*/
if(!FileUtil.isAllowUpImg(fileName)){
throw new IllegalArgumentException("不被允许的上传文件类型");
}
/*
生成文件的路径
*/
String ext = FileUtil.getFileExt(fileName);
fileName = DateUtil.toString(new Date(), "mmss") + StringUtil.getRandStr(4) + "." + ext;
String static_server_path= SystemSetting.getStatic_server_path();
String filePath = static_server_path + "/attachment/";
if(subFolder!=null){
filePath+=subFolder +"/";
}
Calendar now = Calendar.getInstance();
int year=now.get(Calendar.YEAR);
int month=now.get(Calendar.MONTH) + 1;
int date=now.get(Calendar.DAY_OF_MONTH);
int minute=now.get(Calendar.HOUR_OF_DAY);
String timePath="";
if(year!=0){
timePath+=year+"/";;
}
if(month!=0){
timePath+=month+"/";;
}
if(date!=0){
timePath+=date+"/";;
}
if(minute!=0){
timePath+=minute+"/";;
}
String path = EopSetting.FILE_STORE_PREFIX+ "/attachment/" +(subFolder==null?"":subFolder)+"/"+timePath+"/"+fileName;
filePath +=timePath;
filePath += fileName;
/**
* 写入文件 将文件写出
*/
FileUtils.copyInputStreamToFile(stream, new File(filePath));
} else {
System.out.println("不允许上传的文件格式,请上传gif,jpg,bmp,swf格式文件。");
}
}
}
/**
* 是否是允许上传的图片格式
* @param imgFileName
* @return
*/
public static boolean isAllowUpImg(String imgFileName){
imgFileName = imgFileName.toLowerCase();
String allowTYpe = "gif,jpg,bmp,png,jpeg,swf,mp4";
if (!imgFileName.trim().equals("") && imgFileName.length() > 0) {
String ex = imgFileName.substring(imgFileName.lastIndexOf(".") + 1, imgFileName.length());
return allowTYpe.toUpperCase().indexOf(ex.toUpperCase()) >= 0;
} else {
return false;
}
}
form表单就很简单
在测试过程中遇到一个问题
org.springframework.web.multipart.MultipartException: The current request is not a multipart request
当时就是应为没有写 enctype='multipart/form-data'
参考链接