您的位置:首页 > 其它

common-fileupload上传文件

2011-03-16 09:51 435 查看
使用common-fileupload上传文件比较简单,先去 http://commons.apache.org/fileupload/ 下载好相关的jar包,然后准备好上传的页面文件,主要的是一个form,如下:

<form action="uploadFile.do" method="post" enctype="multipart/form-data" name="fileUploadForm"> ... </form>

其中最主要的就是form的enctype属性一定得是"multipart/form-data"。然后就是接受文件的Java类了,这里以Struts的Action为例。

public ActionForward uploadFile(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception
{
ActionForward forward = null;
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
//设置上传文件的大小限制
final long MAX_SIZE = 200 * 1024 * 1024;
//设置上传文件在服务器的目录
String fileFolder = "../webapps/fileupload";
String fileName="";
String contentType="";
String fileSize="";
//从页面传过来的参数值的数组(File除外)
String[] paraArray=new String[3];
int paraNo=0;
//判断该请求是否是文件上传的请求
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
{
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置上传文件时用于临时存放文件的内存大小
factory.setSizeThreshold(100 * 1024);
//设置存放临时文件的目录,这个目录需要事先建立好
factory.setRepository(new File(fileFolder + "/temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAX_SIZE);
upload.setHeaderEncoding("UTF-8");
try
{
List filelist = upload.parseRequest(request);
for (Iterator it = filelist.iterator(); it.hasNext();)
{
FileItem item = it.next();
//判断是form表单域还是上传文件file域
if (item.isFormField())
{
//处理form表单域
String name = new String(item.getFieldName().getBytes("ISO-8859-1"),"UTF-8");
String value =new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");
paraArray[paraNo]=value;
paraNo++;
} else
{
//处理fileUpload
if(item.getSize()>=MAX_SIZE)
{
forward=mapping.findForward("uploadFile");
return forward;
}else
{
int tempSize=(int) (item.getSize()/1024);
if(tempSize*1024                        {
fileSize=tempSize+1+"";
}else
{
fileSize=tempSize+"";
}
String fieldName = item.getFieldName();
//取得文件类型
contentType = item.getContentType();
//文件的全路径
fileName =item.getName();
//得到去除路径的文件名
int index = fileName.lastIndexOf("//");
fileName = fileName.substring(index + 1);
//构建一个文件
File uploadFile = new File(fileFolder, fileName);
//保存文件
item.write(uploadFile);
}
}
}
out.print("UploadFile Successfully !");
//FileService.saveFile(paraArray);
} catch (FileUploadException e)
{
out.print("File is too large,maxsize is 200MB !");
} catch (Exception e)
{
logger.debug(e);
}
}
out.flush();
out.close();
return forward;
}


代码是在英文操作系统下运行的,所以需要将传过来的参数转码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: