需要引入commons-相关的包
String path = "";// 初始化为空,变量作用存储上传文件在服务器上的路径名
String filepath = "";
int number = 0;// 变量表示上传图片的状态,初始化为0表示,上传错误
try {
// DiskFileItem工厂,主要用来设定上传文件的参数
DiskFileItemFactory factory = new DiskFileItemFactory();
// 上传文件所用到的缓冲区大小,超过此缓冲区的部分将被写入到磁盘
factory.setSizeThreshold(4 * 1024);
// 使用fileItemFactory为参数实例化一个ServletFileUpload对象
ServletFileUpload upload = new ServletFileUpload(factory);
// 要求上传的form-data数据不超过100M
upload.setSizeMax(100 * 1024 * 1024);
upload.setHeaderEncoding("utf-8");
// java.util.List实例来接收上传的表单数据和文件数据
List
itemList = upload.parseRequest(request);
Iterator it = itemList.iterator();
FileItem item = (FileItem) it.next();
String uploadPath = request.getRealPath("/upload");
String totalName = item.getName();
int fileSize = item.getInputStream().available();
if (totalName.equals("")) {
number = 2;// 2表示未选择文件
} else if (fileSize > maxSize * 1024 * 1024) {
number = 3;// 3表示文件过大
} else {
int index = totalName.lastIndexOf("/");
String name = "";
name = totalName.substring(index + 1);
String suffix = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
boolean f = false;
if (allowedType != null && !"".equals(allowedType)) {
String[] allowedFile = allowedType.split(",");
for (int i = 0; i < allowedFile.length; i++) {
if (suffix.equals(allowedFile[i].trim())) {
f = true;
}
}
}
if (!f) {
number = 4;// 4表示文件格式错误
} else {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String usepicname = (df.format(new Date()));
Random ran = new Random();
usepicname = usepicname + ran.nextInt(10000);
path = uploadPath + "/" + usepicname + "." + suffix;// 输出到文件
item.write(new File(path));
number = 1;// 1表示上传成功
filepath = "../upload/" + usepicname + "." + suffix;
}
}
EUploadData.put("number", number);
EUploadData.put("filepath", filepath);
} catch (Exception e) {
e.printStackTrace();
throw new Exception();
}