?????? 项目运用的struts和spring框架,需要做一个通用的文件上传,文件下载,文件导出功能供调用,研究了几天,终于写出来了,现在贴出第一部分:文件上传ftp
?????? 文件上传用到的apache的commons.fileupload组件,在前台jsp页面,需要将form表单设置enctype="multipart/form-data",设置这个以后,表单里面的参数要通过if (item.isFormField()) {
??? ??????????????? String fieldId = item.getFieldName();
??? ??????????????? String fieldValue = item.getString("utf-8");
}这种方式才能获取到,代码如下:
?
class="java">@Controller public class FileTransferController extends BaseController{ //临时文件存放目录 public String tempPath = FileUtil.getProjectPath()+"\\temp\\"; /** * 文件上传 * @author zheng_liming * @param request * @param response * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @RequestMapping(value = "/fileTransfer/upload", method = RequestMethod.POST) public void upload(HttpServletRequest request,HttpServletResponse response) throws Exception{ //获取fileUpload上传组件的items DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sevletFileUpload = new ServletFileUpload(factory); List fileItems = null; //获取表单值,并校验 String ftpPath = ""; Map<String, Object> map = getFormField(factory,sevletFileUpload,request); if(map.get("success").equals("false")){ super.parseObjectResponse(map); return; }else{ ftpPath = map.get("ftpPath").toString(); fileItems = (List) map.get("fileItems"); } //消息Map Map<String, Object> resultMap = new HashMap<String, Object>(); Map<String, Object> msgMap = new HashMap<String, Object>(); boolean res = false; //临时文件夹如果不存在,则新建 File tempFile = new File(tempPath); if (!tempFile.exists()) { tempFile.mkdir(); } List fileInfo = new ArrayList();//存放所有的文件信息返回给前台 //依次处理每个上传的文件 Iterator iter = fileItems.iterator(); while (iter.hasNext()) { Map<String, Object> tempMap = new HashMap<String, Object>();//每个文件上传成功后,存放文件的信息 FileItem item = (FileItem) iter.next(); if (!item.isFormField()) {// 忽略其他不是文件域的所有表单信息 String name = item.getName(); long size = item.getSize(); if ((name == null || name.equals("")) && size == 0) continue; //将文件写入临时文件 name = name.replaceAll("\\\\", "/"); name = name.substring(name.lastIndexOf("/")+1); String filePath = tempPath+name; File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } item.write(file); //连接ftp FtpClient ftpClient = FtpUtil.connectServer(ftpPath); //文件上传 boolean uploadResult = FileUtil.ftpUpload(ftpClient,name,filePath); //关闭ftp连接 FtpUtil.closeConnect(ftpClient); if(uploadResult){ tempMap.put("fileName",name); tempMap.put("fileSize",size); tempMap.put("filePath",ftpPath); fileInfo.add(tempMap); res = true; }else{ res = false; break; } } } msgMap.put("msg", res?"上传成功!":"上传失败!"); resultMap.put("msg", msgMap); resultMap.put("success", res?"true":"false"); resultMap.put("fileInfo", fileInfo); //所有操作完成后删除临时文件及文件夹 FileUtil.removeAllFile(tempPath); FileUtil.removeFolder(tempPath); //返回是否成功的消息与文件信息 super.parseObjectResponse(resultMap); } /** * 获取上传时的表单参数并校验 * @author zheng_liming * @param factory * @param sevletFileUpload * @param request * @return */ @SuppressWarnings("rawtypes") public Map<String, Object> getFormField(DiskFileItemFactory factory,ServletFileUpload sevletFileUpload,HttpServletRequest request) throws Exception{ //返回校验的消息 Map<String, Object> result = new HashMap<String, Object>(); Map<String, Object> msg = new HashMap<String, Object>(); //判断表单是否设置enctype="multipart/form-data" boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart == true) { String fileSizeMax = null; String[] allowFileType = null; String[] forbidFileType = null; String filePath = null; List fileItems = sevletFileUpload.parseRequest(request); //获取表单的值 Iterator formFielditer = fileItems.iterator(); while (formFielditer.hasNext()) { FileItem item = (FileItem) formFielditer.next(); if (item.isFormField()) { String fieldId = item.getFieldName(); String fieldValue = item.getString("utf-8"); fieldId = new String(fieldId.getBytes(),"utf-8"); fieldValue = new String(fieldValue.getBytes(),"utf-8"); if(fieldId.equalsIgnoreCase("fileSizeMax")){ fileSizeMax = fieldValue; }else if(fieldId.equalsIgnoreCase("allowFileType")){ allowFileType = fieldValue.split(","); }else if(fieldId.equalsIgnoreCase("forbidFileType")){ forbidFileType = fieldValue.split(","); }else if(fieldId.equalsIgnoreCase("filePath")){ filePath = fieldValue; } } } //设置允许用户上传文件大小,单位:字节 if(fileSizeMax!=null){ sevletFileUpload.setSizeMax(Long.parseLong(fileSizeMax)); try { sevletFileUpload.parseRequest(request); } catch (FileUploadException e) { result.put("success", "false"); msg.put("msg", "文件大小超过限制!"); result.put("msg", msg); return result; } } boolean validate = true; Iterator tempiter = fileItems.iterator(); //校验文件是否为允许上传的格式 if(allowFileType!=null&&allowFileType.length>0){ int count = 0;//通过校验的文件数 int size = 0;//总共的文件数 while (tempiter.hasNext()) { FileItem item = (FileItem) tempiter.next(); if (!item.isFormField()) { String name = item.getName(); if (name != null && !name.equals("") && item.getSize() != 0) size = size+1; for(int i=0;i<allowFileType.length;i++){ if(name.substring(name.lastIndexOf(".")).equals(allowFileType[i])){ count = count +1; break; } } } } validate = count==size?true:false; }else{ //校验文件是否为禁止上传的格式 if(forbidFileType!=null&&forbidFileType.length>0){ while (tempiter.hasNext()&&validate) { FileItem item = (FileItem) tempiter.next(); if (!item.isFormField()) { String name = item.getName(); if ((name == null || name.equals("")) && item.getSize() == 0) continue; for(int i=0;i<forbidFileType.length;i++){ if(name.substring(name.lastIndexOf(".")).equals(forbidFileType[i])){ validate = false; break; } } } } } } if(!validate){ result.put("success", "false"); msg.put("msg", "有禁止上传的文件格式!"); result.put("msg", msg); return result; } //设置最多只允许在内存中存储的数据,单位:字节 factory.setSizeThreshold(4096); //设置一旦文件大小超过内存中存储的大小时数据存放在硬盘的目录 File tempFile = new File(tempPath); if (!tempFile.exists()) { tempFile.mkdir(); } factory.setRepository(tempFile); result.put("success", "true"); result.put("ftpPath", filePath); result.put("fileItems", fileItems); return result; } else { result.put("success", "false"); msg.put("msg", "enctype必须为:multipart/form-data"); result.put("msg", msg); return result; } } }
?
?