package com.want.common;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;import javax.servlet.http.HttpServletRequest;import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;import com.want.util.DateUtil;
import com.want.util.StringUtil;
import com.want.util.Validator;public class UploadBeans { private String errorMsg = ""; public String getErrorMsg()
{
return this.errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
} public String save(HttpServletRequest request, String uploadName, String webPath)
throws Exception
{
return save(request, uploadName, webPath, true);
}
public String save(HttpServletRequest request, String uploadName, String webPath, boolean dataStr)
throws Exception
{
try
{
setErrorMsg("");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fu = new ServletFileUpload(factory);
fu.setSizeMax(1024000L);
factory.setSizeThreshold(4096);
Map paramMap = getParameterMap(fu, request, uploadName);
FileItem fileItem = (FileItem)paramMap.get("uploadFileItem"); String dateString = DateUtil.formatDate(new Date());
String path = webPath;
if (dataStr) path = path + dateString; if (fileItem != null && fileItem.getSize() > 0L) {
if (!validateSuffix(StringUtil.getNotNullStr(paramMap.get("fileSuffix")))) {
setErrorMsg("文件格式不正确!");
return "false";
}
if (!validateSize(fileItem, request.getParameter("maxSize"))) {
setErrorMsg("文件太大!");
return "false";
} File f = new File(path);
if (!f.exists())f.mkdirs(); String fileName = UploadHelper.getMathStringByLength(10) + (String)paramMap.get("fileSuffix");
UploadAttachment.deleteFileByFullName(path + "/" + fileName);
fileItem.write(new File(path + "/" + fileName)); if (dataStr)return dateString + "/" + fileName;
return fileName;
}
setErrorMsg("文件不存在!");
return "false";
}catch (Exception e) {
e.printStackTrace();
setErrorMsg("保存文件时出错!");
}
return "false";
}
private Map getParameterMap(ServletFileUpload fu, HttpServletRequest request, String uploadName)
throws FileUploadException
{
Map parMap = new HashMap(); FileItem fileItem = ((CommonsMultipartFile)((DefaultMultipartHttpServletRequest)request).getFileMap().get(uploadName)).getFileItem();
if (fileItem != null && fileItem.getSize() > 0L) {
String suffix = UploadHelper.getFileSuffix(fileItem.getName());
parMap.put("fileSuffix", suffix);
parMap.put("uploadFileItem", fileItem);
}
return parMap;
}
public String save2(HttpServletRequest request, String uploadName, String webPath, boolean dataStr)
throws Exception{
String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
//最大文件大小
long maxSize = 1000000;
String dateString = DateUtil.formatDate(new Date());
String path = webPath;
if (dataStr) path = path + dateString;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
long fileSize = item.getSize();
if (!item.isFormField()) {
//检查文件大小
if(item.getSize() > maxSize){
setErrorMsg("上传文件大小超过限制。");
return "false";
}
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(fileTypes).contains(fileExt)){
setErrorMsg("上传文件扩展名是不允许的扩展名。");
return "false";
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try{
File uploadedFile = new File(path, newFileName);
item.write(uploadedFile);
}catch(Exception e){
setErrorMsg("上传文件失败。");
return "false";
} if (dataStr) return dateString + "/" + newFileName;
return newFileName;
}
}
return "";
}
public String save3(HttpServletRequest request, File uploadFile, String fileName, String webPath, boolean dataStr)
throws Exception{
String[] fileTypes = new String[]{".gif", ".jpg", ".jpeg", ".png", ".bmp", ".xls" ,".xlsx"};
String newFileName = "";
String dateString = DateUtil.formatDate(new Date()); //按时间日期建立目录
try
{
String fileExt = getExtention(fileName);
if(!Arrays.<String>asList(fileTypes).contains(fileExt)){
setErrorMsg("上传文件扩展名是不允许的扩展名。");
return "false";
} newFileName = UploadHelper.getMathStringByLength(16) + getExtention(fileName);
if (dataStr) webPath = webPath + "/" + dateString;
File f = new File(webPath);
if(!f.exists()) f.mkdirs();
webPath = webPath + "/" + newFileName;
File desFile = new File(webPath);
copy(uploadFile, desFile);
}catch (Exception e) {
e.printStackTrace();
setErrorMsg("保存文件时出错!");
return "false";
}
if (dataStr) return dateString + "/" + newFileName;
return newFileName;
}
public static void copy(File src, File dst) {
InputStream in = null;
OutputStream out = null;
int BUFFER_SIZE = 8192;
try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int c;
while ((c = in.read(buffer)) > 0) {
out.write(buffer, 0, c);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.close();
}
if (null != in) {
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }
/**
* @param fileName
* @return
*/
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
private boolean validateSuffix(String suffix)
{
String permission = ",jpg,bmp,gif,jpeg,png,xls,txt,";
if (suffix == null || suffix.trim().length() < 1) {
return false;
}
return permission.contains("," + suffix.substring(1).toLowerCase() + ",");
}
private boolean validateSize(FileItem fileItem, String maxSizeString)
{
long maxSize = 1024000L;
if (Validator.isNotNull(maxSizeString)) {
maxSize = Long.parseLong(maxSizeString) * 1024L;
} if (maxSize > 1024000L)
{
maxSize = 1024000L;
} return fileItem.getSize() <= maxSize;
}
}
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;import javax.servlet.http.HttpServletRequest;import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;import com.want.util.DateUtil;
import com.want.util.StringUtil;
import com.want.util.Validator;public class UploadBeans { private String errorMsg = ""; public String getErrorMsg()
{
return this.errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
} public String save(HttpServletRequest request, String uploadName, String webPath)
throws Exception
{
return save(request, uploadName, webPath, true);
}
public String save(HttpServletRequest request, String uploadName, String webPath, boolean dataStr)
throws Exception
{
try
{
setErrorMsg("");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fu = new ServletFileUpload(factory);
fu.setSizeMax(1024000L);
factory.setSizeThreshold(4096);
Map paramMap = getParameterMap(fu, request, uploadName);
FileItem fileItem = (FileItem)paramMap.get("uploadFileItem"); String dateString = DateUtil.formatDate(new Date());
String path = webPath;
if (dataStr) path = path + dateString; if (fileItem != null && fileItem.getSize() > 0L) {
if (!validateSuffix(StringUtil.getNotNullStr(paramMap.get("fileSuffix")))) {
setErrorMsg("文件格式不正确!");
return "false";
}
if (!validateSize(fileItem, request.getParameter("maxSize"))) {
setErrorMsg("文件太大!");
return "false";
} File f = new File(path);
if (!f.exists())f.mkdirs(); String fileName = UploadHelper.getMathStringByLength(10) + (String)paramMap.get("fileSuffix");
UploadAttachment.deleteFileByFullName(path + "/" + fileName);
fileItem.write(new File(path + "/" + fileName)); if (dataStr)return dateString + "/" + fileName;
return fileName;
}
setErrorMsg("文件不存在!");
return "false";
}catch (Exception e) {
e.printStackTrace();
setErrorMsg("保存文件时出错!");
}
return "false";
}
private Map getParameterMap(ServletFileUpload fu, HttpServletRequest request, String uploadName)
throws FileUploadException
{
Map parMap = new HashMap(); FileItem fileItem = ((CommonsMultipartFile)((DefaultMultipartHttpServletRequest)request).getFileMap().get(uploadName)).getFileItem();
if (fileItem != null && fileItem.getSize() > 0L) {
String suffix = UploadHelper.getFileSuffix(fileItem.getName());
parMap.put("fileSuffix", suffix);
parMap.put("uploadFileItem", fileItem);
}
return parMap;
}
public String save2(HttpServletRequest request, String uploadName, String webPath, boolean dataStr)
throws Exception{
String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
//最大文件大小
long maxSize = 1000000;
String dateString = DateUtil.formatDate(new Date());
String path = webPath;
if (dataStr) path = path + dateString;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
long fileSize = item.getSize();
if (!item.isFormField()) {
//检查文件大小
if(item.getSize() > maxSize){
setErrorMsg("上传文件大小超过限制。");
return "false";
}
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(fileTypes).contains(fileExt)){
setErrorMsg("上传文件扩展名是不允许的扩展名。");
return "false";
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try{
File uploadedFile = new File(path, newFileName);
item.write(uploadedFile);
}catch(Exception e){
setErrorMsg("上传文件失败。");
return "false";
} if (dataStr) return dateString + "/" + newFileName;
return newFileName;
}
}
return "";
}
public String save3(HttpServletRequest request, File uploadFile, String fileName, String webPath, boolean dataStr)
throws Exception{
String[] fileTypes = new String[]{".gif", ".jpg", ".jpeg", ".png", ".bmp", ".xls" ,".xlsx"};
String newFileName = "";
String dateString = DateUtil.formatDate(new Date()); //按时间日期建立目录
try
{
String fileExt = getExtention(fileName);
if(!Arrays.<String>asList(fileTypes).contains(fileExt)){
setErrorMsg("上传文件扩展名是不允许的扩展名。");
return "false";
} newFileName = UploadHelper.getMathStringByLength(16) + getExtention(fileName);
if (dataStr) webPath = webPath + "/" + dateString;
File f = new File(webPath);
if(!f.exists()) f.mkdirs();
webPath = webPath + "/" + newFileName;
File desFile = new File(webPath);
copy(uploadFile, desFile);
}catch (Exception e) {
e.printStackTrace();
setErrorMsg("保存文件时出错!");
return "false";
}
if (dataStr) return dateString + "/" + newFileName;
return newFileName;
}
public static void copy(File src, File dst) {
InputStream in = null;
OutputStream out = null;
int BUFFER_SIZE = 8192;
try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int c;
while ((c = in.read(buffer)) > 0) {
out.write(buffer, 0, c);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.close();
}
if (null != in) {
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }
/**
* @param fileName
* @return
*/
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
private boolean validateSuffix(String suffix)
{
String permission = ",jpg,bmp,gif,jpeg,png,xls,txt,";
if (suffix == null || suffix.trim().length() < 1) {
return false;
}
return permission.contains("," + suffix.substring(1).toLowerCase() + ",");
}
private boolean validateSize(FileItem fileItem, String maxSizeString)
{
long maxSize = 1024000L;
if (Validator.isNotNull(maxSizeString)) {
maxSize = Long.parseLong(maxSizeString) * 1024L;
} if (maxSize > 1024000L)
{
maxSize = 1024000L;
} return fileItem.getSize() <= maxSize;
}
}
2、你的代码注释太少
3、你要问什么?
我想写个上传文件的方法同学发给我的。。