Extjs通过Apache的FileItem进行文件的上传下载
一.上传
1.Extjs:
在FormPanel中要增加一个属性:[ fileUpload : true ]
var addNewsForm = new Ext.form.FormPanel({ id:"addNewsForm", frame:true, layout:"form", labelAlign:"right", labelWidth:"150", buttonAlign:"center", fileUpload : true, items:[{ id:"id", name:"id", xtype:"textfield", fieldLabel:"编号", hidden:true, hideLabel:true },{ id:"title", name:"title", xtype:"textfield", fieldLabel:"新闻标题", allowBlank:false, minLength:5, maxLength:50, width:750 },{ id:"tag", name:"tag", xtype:"textarea", fieldLabel:"新闻标签", allowBlank:false, maxLength:330, height:70, width:750 },{ name:"content", xtype:"StarHtmleditor", fieldLabel:"新闻内容", fontFamilies: ["宋体","隶书","黑体","楷体","幼圆"], width:750, height:230 },typeRadio,statusRadio,{ id:"ishot", name:"ishot", xtype:"checkbox", fieldLabel:"是否热点" },{ id:"uploadNews", name:"uploadNews", xtype:"textfield", inputType:"file", fieldLabel:"上传文件", buttonText: '' }], buttons:[{ text:"确定", handler:addNews },{ text:"取消", handler:function(){ history.go(-1); } }] });
注意:当增加了该属性后,form表单提交到后台,textfield文本框的值用request获取将为null,所以此时我们需要用到Apache的FileItem来实现文本框的值的获取和上传文件的文件名。
2.获取表单提交请求的Servlet:
String title = ""; String tag = ""; String content = ""; String typeStr = "0"; String ishotStr = "0"; String statusStr = "0"; String uploadFileName = ""; Long time = System.currentTimeMillis(); Calendar cal=Calendar.getInstance(); int year=cal.get(Calendar.YEAR);//得到年 int month=cal.get(Calendar.MONTH)+1;//得到月 String newsFileDir = Configuration.getConfig().getString("newsFileDir");//从Resource.properties中读取配置信息 if (newsFileDir.contains("/")) { newsFileDir = newsFileDir.replace("/", File.separator); } String uploadFileDir = newsFileDir + File.separator + year + File.separator +month; List<FileItem> fileItems = UploadFileUtil.getServletFileUpload().parseRequest(request);//解析Request请求 for (int i = 0; i < fileItems.size(); i++) { FileItem item = fileItems.get(i); if (!item.isFormField()) {//判断是否是表单文本域——即不是上传文件域! uploadFileName = item.getName(); Map<String, String> map = UploadFileUtil.uploadFile(uploadFileDir, item); if (map.get("msg") != null) { response.setContentType("text/html;charset=UTF-8"); out=response.getWriter(); out.print("{failure:\""+map.get("msg")+"\"}"); out.close(); return; } } else { String newsStr = new String(item.getString().getBytes("ISO8859_1"), "UTF-8");//解决中文乱码 if ("title".equals(item.getFieldName())) { title = newsStr;//将FileItem对象中保存的数据流内容以一个字符串返回。 } else if ("tag".equals(item.getFieldName())) { tag = newsStr; } else if ("content".equals(item.getFieldName())) { content = newsStr; } else if ("type".equals(item.getFieldName())) { typeStr = newsStr; } else if ("status".equals(item.getFieldName())) { statusStr = newsStr; } else if ("ishot".equals(item.getFieldName())) { ishotStr = newsStr; } } } int type = Integer.valueOf(typeStr); int status = Integer.valueOf(statusStr); int ishot = 0; if("on".equals(ishotStr)){ ishot = 1; } INewsDao newsDao = new NewsDaoImpl(); News news = new News(); news.setTitle(title); news.setTag(tag); news.setType(type); news.setIshot(ishot); news.setContent(clob); news.setStatus(status); news.setUploadDir(uploadFileDir); news.setUploadFile(uploadFileName); done = newsDao.saveNews(news); String str =null; if(done){ str="{success:true}"; }else{ str="{success:false}"; } response.setContentType("text/html;charset=UTF-8"); out=response.getWriter(); out.print(str); out.close(); return;
注意:
(1).需要通过 item.isFormField() 来判断是普通表单域还是上传域;
(2).一定要对获取到的数据流(即普通表单域中的内容)进行解码,否则会出现中文乱码!
(FileItem类的getString方法用于将FileItem对象中保存的数据流内容以一个字符串返回)
——保存的数据流内容即普通文本域(非上传域)的内容!
3.上传文件工具类:
package com.datanew.czfc.util; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; 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; /** * 创建人: zy * 创建时间: 2014年12月4日 下午2:46:38 * 类描述:上传文件工具类 */ public class UploadFileUtil { /** * 获取ServletFileUpload * @return */ public static ServletFileUpload getServletFileUpload(){ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); return upload; } /** * 上传文件 * @param fileDir * @param fileItem * @return */ public static Map<String, String> uploadFile(String fileDir,FileItem fileItem) { String fileName = null; long maxSize = 5*1024*1024; Map<String, String> map = new HashMap<String, String>(); try { //1.判断目录是否存在,不存在则创建目录 String[] paths; if (fileDir.contains("/")) { paths = fileDir.split("/"); } else { paths = fileDir.split("\\\\");//注意:此处“\\”是错误的,必须要“\\\\”才能分割字符串 } String dir = paths[0]; for (int i = 1; i < paths.length; i++) { dir = dir + File.separator + paths[i]; File file=new File(dir.toString()); if (!file.exists()) { file.mkdir(); } } //2.保存文件 fileName = fileItem.getName(); if (fileName == "" || fileName == null) { map.put("msg", "请先上传文件"); return map; } long size = fileItem.getSize(); if (size > maxSize) { map.put("msg", "您上传的文件过大,请重新上传"); return map; } //fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf(".")); map.put("fileName", fileName); fileItem.write(new File(fileDir + File.separator +fileName)); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return map; } }
注意:
1.要对ServletFileUpload进行编码的设置;
2.采用fileItem.write的方式进行文件的写操作,即上传文件到指定的目录;
二.下载:
通过新闻标题查询实体类,在通过获取的实体类中的文件路径进行文件的下载
else if ("getFile".equals(action)) { String title = new String(request.getParameter("title").getBytes("ISO8859_1"), "UTF-8"); INewsDao newsDao = new NewsDaoImpl(); String filePath = newsDao.getFile(title); String str =null; try { File file = new File(filePath); response.setContentType("text/plain"); //response.setHeader("Location",fileName); response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("GBK"), "iso-8859-1")); OutputStream os = response.getOutputStream(); InputStream inputStream = new FileInputStream(file); byte[] buffer = new byte[1024]; int i = -1; while ((i = inputStream.read(buffer)) != -1) { os.write(buffer, 0, i); } os.flush(); os.close(); } catch (FileNotFoundException e) { System.out.println("文件未找到"); } return; }
注意:
1.要对request获取的中文进行编码;![](http://dl2.iteye.com/upload/attachment/0104/2838/89539b01-c6dd-3a6f-a0f8-5df476ad4129.png)
2.要对response的ContentType和Header进行设置;
实例图示:
实例中解析Request获得的FileItem数据:
[ name=null, StoreLocation=C: \Users\ADMINI~1\AppData\Local\Temp\upload__42856ff_14a38191494__8000_00000000.tmp, size=0bytes, isFormField=true, FieldName=id, name=null, StoreLocation=C: \Users\ADMINI~1\AppData\Local\Temp\upload__42856ff_14a38191494__8000_00000001.tmp, size=24bytes, isFormField=true, FieldName=title, name=null, StoreLocation=C: \Users\ADMINI~1\AppData\Local\Temp\upload__42856ff_14a38191494__8000_00000002.tmp, size=18bytes, isFormField=true, FieldName=tag, name=null, StoreLocation=C: \Users\ADMINI~1\AppData\Local\Temp\upload__42856ff_14a38191494__8000_00000003.tmp, size=36bytes, isFormField=true, FieldName=content, name=null, StoreLocation=C: \Users\ADMINI~1\AppData\Local\Temp\upload__42856ff_14a38191494__8000_00000004.tmp, size=1bytes, isFormField=true, FieldName=type, name=null, StoreLocation=C: \Users\ADMINI~1\AppData\Local\Temp\upload__42856ff_14a38191494__8000_00000005.tmp, size=1bytes, isFormField=true, FieldName=status, name=null, StoreLocation=C: \Users\ADMINI~1\AppData\Local\Temp\upload__42856ff_14a38191494__8000_00000006.tmp, size=2bytes, isFormField=true, FieldName=ishot, name=test.txt, StoreLocation=C: \Users\ADMINI~1\AppData\Local\Temp\upload__42856ff_14a38191494__8000_00000007.tmp, size=418bytes, isFormField=false, FieldName=uploadNews, name=null, ]
数据分析:
1.蓝框的是普通表单域的内容
2.红框的是上传域的内容
3.FieldName是表单中的某个item项的name