ajaxFileUpload文件上传后台通用代码

前端之家收集整理的这篇文章主要介绍了ajaxFileUpload文件上传后台通用代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Properties;
importjava.text.SimpleDateFormat;
importjavax.servlet.http.HttpServletRequest;

importorg.apache.commons.fileupload.DiskFileUpload;
importorg.apache.commons.fileupload.FileItem;
importorg.apache.commons.fileupload.FileUploadException;
importorg.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
importorg.apache.log4j.Logger;

//importsun.util.logging.resources.logging;


/**
*通用文件上传
*
*@authorWang
*@date2013-07-20
*/
publicclassUpload{

/**
*上传后,将InputStream保存到封装的map中
*/
publicstaticintFILESTREAM=1;
/**
*上传后,将文件转化为二进制保存
*/
publicstaticintFILEBYTES=2;
/**
*
*/
publicstaticintFILE=3;


privateStringfileName="";

publicStringgetFileName(){
returnfileName;
}

publicvoidsetFileName(StringfileName){
this.fileName=fileName;
}
privatestaticStringfilePath="";
privatestaticlongmaxUploadSize=1024*512*1024;
privatestaticStringheaderEncoding="UTF-8";
Loggerlog=Logger.getLogger(getClass());

/**
*默认上传最大上限
*保存类型为FILESTREAM
*@paramrequest
*@return
*/
publicMapupload(HttpServletRequestrequest){
returnupload(request,maxUploadSize,FILESTREAM);
}

/**
*判断filePhth路径中是否存在该文件夹,不存在则创建该文件夹
*创建成功则返回True
*@paramfilePhth
*@return
**/
publicbooleancreateFile(StringfilePhth){
FiledirFile;
booleanbFile=false;
try{
dirFile=newFile(filePhth);
bFile=dirFile.exists();
if(bFile!=true){
bFile=dirFile.mkdir();
}
}catch(Exceptione)
{
}
returnbFile;
}

static{
Propertiesr=PropertiesHelper.loadProperty("/upload.properties");
if(!r.isEmpty()){
try{
filePath=r.getProperty("filePath");

}catch(Exceptione){
Logger.getLogger(Upload.class).error("无法读filePath参数",e);
}
try{
headerEncoding=r.getProperty("headerEncoding");

}catch(Exceptione){
Logger.getLogger(Upload.class).error("无法读headerEncoding参数",e);
}
try{
maxUploadSize=Long.parseLong(String.valueOf(r.get("maxUploadSize")));
}catch(Exceptione){
Logger.getLogger(Upload.class).error("无法读maxUploadSize参数",e);
}}else{
Logger.getLogger(Upload.class).error("无法读取upload.properties");
}
}




/**
*@paramrequest
*@paramsize上传文件大小上限
*@paramtype保存类型1、保存InputStream,2保存bytes
*@return
*/
publicMapupload(HttpServletRequestrequest,longsize,inttype){

Mapmap=newHashMap();
DiskFileUploadfileUpload=newDiskFileUpload();
fileUpload.setSizeMax(size==0?maxUploadSize:size);//最大上传大小
fileUpload.setHeaderEncoding("UTF-8");
fileUpload.setSizeThreshold(4096);
SimpleDateFormatsdf=newSimpleDateFormat("yyyyMM");
FileItemfileItem=null;
StringoldFileName="";
try{
ListitemList=fileUpload.parseRequest(request);
for(Iteratoriterator=itemList.iterator();iterator.hasNext();){
fileItem=(FileItem)iterator.next();
System.out.println("--------maps----------"+fileItem.isFormField());
if(fileItem.isFormField()){
map.put(fileItem.getFieldName(),fileItem.getString());
}else{
if(type==FILESTREAM){
map.put(fileItem.getFieldName(),fileItem.getInputStream());
}elseif(type==FILEBYTES){
InputStreamin=fileItem.getInputStream();
byte[]b=newbyte[in.available()];
in.read(b);
map.put(fileItem.getFieldName(),b);
}else{
StringstrPhthString=filePath+File.separator+File.separator;
oldFileName=fileItem.getName();
map.put("FILE_NAME",oldFileName.substring(oldFileName.lastIndexOf(File.separator)+1,oldFileName.length()));
map.put("FILE_SIZE",newLong(fileItem.getSize()));
fileName=fileName+oldFileName.substring(oldFileName.lastIndexOf("."),oldFileName.length());//存储文件名;

map.put(fileItem.getFieldName(),fileName);//该参数为生成文件夹和文件名连在一起
createFile(strPhthString);
map.put("FILE_PATH",fileName);

fileItem.write(newFile(strPhthString+fileName));
}
}
}
log.error("upload:"+map);
returnmap;
}catch(SizeLimitExceededExceptione){
map.clear();
map.put("error","filetolarge.Themaxsizeis"+fileUpload.getSizeMax());
}catch(FileUploadExceptione){
map.clear();
map.put("error",e.getMessage());
}catch(IOExceptione){
map.clear();
map.put("error",e.getMessage());
}catch(Exceptione){
e.printStackTrace();
map.put("error",e.getMessage());
}
returnmap;
}



/**
*@paramrequest
*@paramsize上传文件大小上限
*@paramtype保存类型1、保存InputStream,2保存bytes
*@return
*/
publicMapupload2(HttpServletRequestrequest,inttype){
Mapmap=newHashMap();
DiskFileUploadfileUpload=newDiskFileUpload();
fileUpload.setSizeMax(size);//最大上传大小
FileItemfileItem=null;
SimpleDateFormatsdf=newSimpleDateFormat("yyyyMM");
StringoldFileName="";
try{
ListitemList=fileUpload.parseRequest(request);
StringstrPhthString=request.getRealPath("/")+"/upimage/"+sdf.format(newDate());
for(Iteratoriterator=itemList.iterator();iterator.hasNext();){
fileItem=(FileItem)iterator.next();
if(fileItem.isFormField()){
map.put(fileItem.getFieldName(),b);
}else{
oldFileName=fileItem.getName();
fileName=CommonUtil.getCurrentDateTime()+oldFileName.substring(oldFileName.indexOf("."),oldFileName.length());

map.put(fileItem.getFieldName(),sdf.format(newDate())+"/"+fileName);//该参数为生成文件夹和文件名连在一起
createFile(strPhthString);
fileItem.write(newFile(strPhthString+"/"+fileName));

}
}
}
log.error("upload:"+map);
returnmap;
}catch(SizeLimitExceededExceptione){
map.clear();
map.put("error","filetolarge.Themaxsizeis"+size);
}catch(FileUploadExceptione){
map.clear();
map.put("error",e.getMessage());
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnmap;
}

}@H_301_1@ 
 

记得引用commons-fileupload.jar 包,调用方式

		Uploadupload=newUpload();

		Stringfjid=Identities.uuid2();//唯一32位编码
		upload.setFileName(fjid);
		intuptype=Upload.FILE;
		Mapmap=upload.upload(getRequest(),uptype);//文件删除
			if(map.isEmpty()){
					setAttr("success",false);
				setAttr("msg","未知");
				renderJson();
			}elseif(map.containsKey("error")){
				setAttr("success",""+map.get("error")+"");
				renderJson();
			}
			//可以将获取文件真实名称文件服务器名称文件路径,文件大小保存数据库
		Stringext=getFileExt((String)map.get("FILE_NAME"));
		Stringwjmc=map.get("FILE_NAME").toString();
		Stringpath=map.get("FILE_PATH").toString();
		Stringarchivesfileid=getPara(0);
		Stringsize=map.get("FILE_SIZE").toString();@H_301_1@

猜你在找的Ajax相关文章