List of usage examples for org.apache.commons.fileupload DiskFileUpload setHeaderEncoding
public void setHeaderEncoding(String encoding)
From source file:com.baobao121.baby.common.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * // ww w . j ava 2s .c o m * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String currentPath = ""; String currentDirPath = ""; String typeStr = request.getParameter("Type"); UserCommonInfo info = null; info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.USER_COMMON_INFO); if (info == null) { info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.ADMIN_INFO); } currentPath = baseDir + "images/"; currentDirPath = getServletContext().getRealPath(currentPath); if (!(new File(currentDirPath).isDirectory())) { new File(currentDirPath).mkdir(); } if (info.getObjectTableName() == null || info.getObjectTableName().equals("")) { currentPath += "admin/"; } else { if (info.getObjectTableName().equals(SystemConstant.BABY_INFO_TABLE_NAME)) { currentPath += "babyInfo/"; } if (info.getObjectTableName().equals(SystemConstant.KG_TEACHER_INFO_TABLE_NAME)) { currentPath += "teacherInfo/"; } } currentDirPath = getServletContext().getRealPath(currentPath); if (!(new File(currentDirPath).isDirectory())) { new File(currentDirPath).mkdir(); } currentPath += info.getId(); currentDirPath = getServletContext().getRealPath(currentPath); if (!(new File(currentDirPath).isDirectory())) { new File(currentDirPath).mkdir(); } if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new DiskFileUpload(); try { upload.setHeaderEncoding("utf-8"); List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); InputStream is = uplFile.getInputStream(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; Calendar calendar = Calendar.getInstance(); String nameWithoutExt = String.valueOf(calendar.getTimeInMillis()); ; String ext = getExtension(fileName); fileName = nameWithoutExt + "." + ext; fileUrl = currentPath + "/" + fileName; if (extIsAllowed(typeStr, ext)) { FileOutputStream desc = new FileOutputStream(currentDirPath + "/" + fileName); changeDimension(is, desc, 450, 1000); if (info.getObjectTableName() != null && !info.getObjectTableName().equals("")) { Photo photo = new Photo(); photo.setPhotoName(fileName); PhotoAlbum album = babyAlbumDao.getMAlbumByUser(info.getId(), info.getObjectTableName()); if (album.getId() != null) { Long albumId = album.getId(); photo.setPhotoAlbumId(albumId); photo.setPhotoLink(fileUrl); photo.setDescription(""); photo.setReadCount(0L); photo.setCommentCount(0L); photo.setReadPopedom("1"); photo.setCreateTime(DateUtil.getCurrentDateTimestamp()); photo.setModifyTime(DateUtil.getCurrentDateTimestamp()); babyPhotoDao.save(photo); babyAlbumDao.updateAlbumCount(albumId); } } } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("?: " + ext); } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "??"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + request.getContextPath() + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobDAOImpl.java
@Override public void parseRequest(HttpServletRequest request, HashMap<String, Object> arrParam, ArrayList<FileItem> fi, boolean fileUpload, HashMap<Integer, String> filemap) { DiskFileUpload fu = new DiskFileUpload(); FileItem fi1 = null;// w w w. j ava 2 s. c o m List fileItems = null; int i = 0; try { fu.setHeaderEncoding("UTF-8"); fileItems = fu.parseRequest(request); } catch (FileUploadException e) { // throw ServiceException.FAILURE("Admin.createUser", e); } for (Iterator k = fileItems.iterator(); k.hasNext();) { fi1 = (FileItem) k.next(); if (fi1.isFormField()) { try { arrParam.put(fi1.getFieldName(), new String(fi1.getString().getBytes("iso-8859-1"), "UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { String fileName = new String(fi1.getName().getBytes(), "UTF8"); if (fi1.getSize() != 0) { fi.add(fi1); filemap.put(i, fi1.getFieldName()); i++; fileUpload = true; } } catch (UnsupportedEncodingException ex) { } } } }
From source file:org.apache.struts.upload.CommonsMultipartRequestHandler.java
/** * <p> Parses the input stream and partitions the parsed items into a set * of form fields and a set of file items. In the process, the parsed * items are translated from Commons FileUpload <code>FileItem</code> * instances to Struts <code>FormFile</code> instances. </p> * * @param request The multipart request to be processed. * @throws ServletException if an unrecoverable error occurs. */// ww w. j a v a 2s . c o m public void handleRequest(HttpServletRequest request) throws ServletException { // Get the app config for the current request. ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY); // Create and configure a DIskFileUpload instance. DiskFileUpload upload = new DiskFileUpload(); // The following line is to support an "EncodingFilter" // see http://issues.apache.org/bugzilla/show_bug.cgi?id=23255 upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax(getSizeMax(ac)); // Set the maximum size that will be stored in memory. upload.setSizeThreshold((int) getSizeThreshold(ac)); // Set the the location for saving data on disk. upload.setRepositoryPath(getRepositoryPath(ac)); // Create the hash tables to be populated. elementsText = new Hashtable(); elementsFile = new Hashtable(); elementsAll = new Hashtable(); // Parse the request into file items. List items = null; try { items = upload.parseRequest(request); } catch (DiskFileUpload.SizeLimitExceededException e) { // Special handling for uploads that are too big. request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE); return; } catch (FileUploadException e) { log.error("Failed to parse multipart request", e); throw new ServletException(e); } // Partition the items into form fields and files. Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { addTextParameter(request, item); } else { addFileParameter(item); } } }
From source file:org.apache.tapestry.multipart.DefaultMultipartDecoder.java
/** * Decodes the request, storing the part map (keyed on query parameter name, * value is {@link IPart} into the request as an attribute. * // ww w. j av a 2 s . c o m * @throws ApplicationRuntimeException if decode fails, for instance the * request exceeds getMaxSize() * **/ public void decode(HttpServletRequest request) { Map partMap = new HashMap(); request.setAttribute(PART_MAP_ATTRIBUTE_NAME, partMap); // The encoding that will be used to decode the string parameters // It should NOT be null at this point, but it may be // if the older Servlet API 2.2 is used String encoding = request.getCharacterEncoding(); // DiskFileUpload is not quite threadsafe, so we create a new instance // for each request. DiskFileUpload upload = new DiskFileUpload(); List parts = null; try { if (encoding != null) upload.setHeaderEncoding(encoding); parts = upload.parseRequest(request, _thresholdSize, _maxSize, _repositoryPath); } catch (FileUploadException ex) { throw new ApplicationRuntimeException( Tapestry.format("DefaultMultipartDecoder.unable-to-decode", ex.getMessage()), ex); } int count = Tapestry.size(parts); for (int i = 0; i < count; i++) { FileItem uploadItem = (FileItem) parts.get(i); if (uploadItem.isFormField()) { try { String name = uploadItem.getFieldName(); String value; if (encoding == null) value = uploadItem.getString(); else value = uploadItem.getString(encoding); ValuePart valuePart = (ValuePart) partMap.get(name); if (valuePart != null) { valuePart.add(value); } else { valuePart = new ValuePart(value); partMap.put(name, valuePart); } } catch (UnsupportedEncodingException ex) { throw new ApplicationRuntimeException(Tapestry.format("illegal-encoding", encoding), ex); } } else { UploadPart uploadPart = new UploadPart(uploadItem); partMap.put(uploadItem.getFieldName(), uploadPart); } } }
From source file:org.araneaframework.servlet.filter.StandardServletFileUploadFilterService.java
protected void action(Path path, InputData input, OutputData output) throws Exception { HttpServletRequest request = ((ServletInputData) input).getRequest(); if (FileUpload.isMultipartContent(request)) { Map fileItems = new HashMap(); Map parameterLists = new HashMap(); // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); if (useRequestEncoding) upload.setHeaderEncoding(request.getCharacterEncoding()); else if (multipartEncoding != null) upload.setHeaderEncoding(multipartEncoding); // Set upload parameters if (maximumCachedSize != null) upload.setSizeThreshold(maximumCachedSize.intValue()); if (maximumSize != null) upload.setSizeMax(maximumSize.longValue()); if (tempDirectory != null) upload.setRepositoryPath(tempDirectory); // Parse the request List items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { fileItems.put(item.getFieldName(), item); } else { List parameterValues = (List) parameterLists.get(item.getFieldName()); if (parameterValues == null) { parameterValues = new ArrayList(); parameterLists.put(item.getFieldName(), parameterValues); }// w w w. j a v a 2s . c o m parameterValues.add(item.getString()); } } log.debug("Parsed multipart request, found '" + fileItems.size() + "' file items and '" + parameterLists.size() + "' request parameters"); output.extend(ServletFileUploadInputExtension.class, new StandardServletFileUploadInputExtension(fileItems)); request = new MultipartWrapper(request, parameterLists); ((ServletOverridableInputData) input).setRequest(request); } super.action(path, input, output); }
From source file:org.craft.xdd.view.servlet.FCKEditorUploaderServlet.java
/** * Manage the Upload requests.<br> * //from w w w.j a v a 2 s . c om * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("--- FCKEditorUploaderServlet BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String typeStr = request.getParameter("Type"); String currentPath = baseDir + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; log.debug(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new DiskFileUpload(); upload.setHeaderEncoding("UTF-8"); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else { fields.put(item.getFieldName(), item); } } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = new String(pathParts[pathParts.length - 1].getBytes(), "GBK"); String timeSerial = new Long(System.currentTimeMillis()).toString(); String ext = getExtension(fileName); fileName = timeSerial + "." + ext; File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (extIsAllowed(typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = timeSerial + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; log.debug("Invalid file type: " + ext); } } catch (Exception ex) { log.debug(ex.getMessage(), ex); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); log.debug("--- FCKEditorUploaderServlet BEGIN DOPOST ---"); }
From source file:org.hdiv.config.multipart.StrutsMultipartConfig.java
/** * Parses the input stream and partitions the parsed items into a set of form fields and a set of file items. * //www . ja v a2 s . co m * @param request * The multipart request wrapper. * @param servletContext * Our ServletContext object * @return multipart processed request * @throws HdivMultipartException * if an unrecoverable error occurs. */ public HttpServletRequest handleMultipartRequest(RequestWrapper request, ServletContext servletContext) throws HdivMultipartException { DiskFileUpload upload = new DiskFileUpload(); upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax(getSizeMax()); // Set the maximum size that will be stored in memory. upload.setSizeThreshold((int) getSizeThreshold()); // Set the the location for saving data on disk. upload.setRepositoryPath(getRepositoryPath(servletContext)); List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (DiskFileUpload.SizeLimitExceededException e) { if (log.isErrorEnabled()) { log.error("Size limit exceeded exception"); } // Special handling for uploads that are too big. throw new HdivMultipartException(e); } catch (FileUploadException e) { if (log.isErrorEnabled()) { log.error("Failed to parse multipart request", e); } throw new HdivMultipartException(e); } // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { this.addTextParameter(request, item); } else { this.addFileParameter(request, item); } } return request; }
From source file:org.jxstar.control.action.ActionHelper.java
/** * ?//ww w . j av a2s .c o m * @param request * @return */ private static Map<String, Object> parseMultiRequest(HttpServletRequest request) throws ActionException { //? DefaultFileItemFactory factory = new DefaultFileItemFactory(); //? DiskFileUpload upload = new DiskFileUpload(factory); //???? upload.setHeaderEncoding("utf-8"); //?10M String maxSize = SystemVar.getValue("upload.file.maxsize", "10"); upload.setSizeMax(1000 * 1000 * Integer.parseInt(maxSize)); //? List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { _log.showError(e); throw new ActionException(JsMessage.getValue("fileaction.overmaxsize"), maxSize); } _log.showDebug("request item size=" + items.size()); // Map<String, Object> requestMap = FactoryUtil.newMap(); // ? Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String key = item.getFieldName(); //????? String value = ""; try { value = item.getString("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (key == null || key.length() == 0) continue; requestMap.put(key, value); } else { String key = item.getFieldName(); requestMap.put(key, item); //?? String fileName = item.getName(); String contentType = item.getContentType(); long fileSize = item.getSize(); _log.showDebug( "request filename=" + fileName + ";fileSize=" + fileSize + ";contentType=" + contentType); } } return requestMap; }