一、用此类的前提
1、jsp页面是用form表单提交 而且 enctype="multipart/form-data" 是一定的
<pre name="code" class="html"><form id="submitForm" method="post" action="***" enctype="multipart/form-data" ><form>
2、只适合传文件类型的,如果有其他type=text的提交是不能直接接受的
package com.hld.util;
import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
*
* @author z
* @date 2015年12月21日上午10:20:57
*/
public class FileUploadUtil {
public static String uploadImg(HttpServletRequest request, String upladPath) throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String saveFileName = null;
String imagePath = upladPath;
String x = request.getParameter("length");
String y = request.getParameter("wide");
if (isMultipart) {
String headShowServicePath = request.getSession().getServletContext()
.getRealPath("/")
+ imagePath;
String fileName = FileUtil.getRandomFileName();
File headShowFile = new File(headShowServicePath);
if (!headShowFile.isDirectory())
headShowFile.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
factory.setRepository(headShowFile);
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setSizeMax(20 * 1024 * 1024);
List<FileItem> fileItems = uploader.parseRequest(request);
for (FileItem item : fileItems) {
if (item.isFormField()) {
String FileDescription = item.getString();
// funName=item.getString();
} else {
String fileRealName=item.getName();
String fix=fileRealName.substring(fileRealName.lastIndexOf(".") + 1).
trim().toLowerCase();
// String fix = type;
fileName += "." + fix;
saveFileName = imagePath + fileName;
File file = new File(headShowServicePath + fileName);
item.write(file);
}
}
// //压缩图片
// if(x!=null&&!"".equals(x) && y!=null&&!"".equals(y)) {
// saveFileName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));
// }
}
return saveFileName;
}
}