Java Code Examples for org.apache.commons.fileupload.servlet.ServletFileUpload#setHeaderEncoding()

The following examples show how to use org.apache.commons.fileupload.servlet.ServletFileUpload#setHeaderEncoding() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ValidateFormService.java    From kk-anti-reptile with Apache License 2.0 5 votes vote down vote up
public String validate(HttpServletRequest request) throws UnsupportedEncodingException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    Map<String, String> params = new HashMap<String, String>();
    for(Object object : items){
        FileItem fileItem = (FileItem) object;
        if (fileItem.isFormField()) {
            params.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
        }
    }
    String verifyId = params.get("verifyId");
    String result =  params.get("result");
    String realRequestUri = params.get("realRequestUri");
    String actualResult = verifyImageUtil.getVerifyCodeFromRedis(verifyId);
    if (actualResult != null && request != null && actualResult.equals(result.toLowerCase())) {
        actuator.reset(request, realRequestUri);
        return "{\"result\":true}";
    }
    return "{\"result\":false}";
}
 
Example 2
Source File: UploadHandleServlet.java    From rainbow with Apache License 2.0 5 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            if (!ServletFileUpload.isMultipartContent(request))
            {
                return;
            }
            this.fileList = upload.parseRequest(request);
//            System.out.println(fileList.size());
            for (FileItem item : fileList)
            {
                if (item.isFormField())
                {
                    String value = item.getString("UTF-8");
//                  System.out.print(value);
                    names.add(value);
                } else
                {
                    String filename = item.getName();
                    if (filename == null) continue;
                    File newFile = new File(filename);
//            		System.out.println(newFile.getCanonicalPath());
//            		item.write(newFile);
                    this.names.add(newFile.getAbsolutePath().toString());
                    saveFile(item);
                }
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
 
Example 3
Source File: AlbianFileUploadService.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void loading() {
    FileUploadConfigurtion fc = c.getFileUploadConfigurtion();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(factory.getRepository());
    upload = new ServletFileUpload(factory);
    this.upload.setSizeMax(fc.getMaxRequestSize());
    this.upload.setHeaderEncoding(c.getCharset());
    this.upload.setFileSizeMax(fc.getMaxFileSize());
    upload.setHeaderEncoding(c.getCharset());

}
 
Example 4
Source File: Uploader.java    From jeewx with Apache License 2.0 5 votes vote down vote up
private void parseParams() {

		DiskFileItemFactory dff = new DiskFileItemFactory();
		try {
			ServletFileUpload sfu = new ServletFileUpload(dff);
			sfu.setSizeMax(this.maxSize);
			sfu.setHeaderEncoding(Uploader.ENCODEING);

			FileItemIterator fii = sfu.getItemIterator(this.request);

			while (fii.hasNext()) {
				FileItemStream item = fii.next();
				// 普通参数存储
				if (item.isFormField()) {

					this.params.put(item.getFieldName(),
							this.getParameterValue(item.openStream()));

				} else {

					// 只保留一个
					if (this.inputStream == null) {
						this.inputStream = item.openStream();
						this.originalName = item.getName();
						return;
					}

				}

			}

		} catch (Exception e) {
			this.state = this.errorInfo.get("UNKNOWN");
		}

	}
 
Example 5
Source File: UploadServlet.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	// �ж��ϴ����Ƿ�����ļ�
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (isMultipart) {
		// ��ȡ·��
		String realpath = request.getSession().getServletContext().getRealPath("/files");
		System.out.println(realpath);

		File dir = new File(realpath);
		if (!dir.exists())
			dir.mkdirs();

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			// ����������� ��ʵ���� form����ÿ��input�ڵ�
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// ����DZ� ����ÿ���� ��ӡ������̨
					String name1 = item.getFieldName();// �õ��������������
					String value = item.getString("UTF-8");// �õ�����ֵ
					System.out.println(name1 + "=" + value);
				} else {
					// ���ļ�д����ǰservlet����Ӧ��·��
					item.write(new File(dir, System.currentTimeMillis()
							+ item.getName().substring(item.getName().lastIndexOf("."))));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 6
Source File: UploadServlet.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	// �ж��ϴ����Ƿ�����ļ�
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (isMultipart) {
		// ��ȡ·��
		String realpath = request.getSession().getServletContext()
				.getRealPath("/files");
		System.out.println(realpath);

		File dir = new File(realpath);
		if (!dir.exists())
			dir.mkdirs();
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			// ����������� ��ʵ���� form����ÿ��input�ڵ�
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// ����DZ� ����ÿ���� ��ӡ������̨
					String name1 = item.getFieldName();// �õ��������������
					String value = item.getString("UTF-8");// �õ�����ֵ
					System.out.println(name1 + "=" + value);
				} else {
					// ���ļ�д����ǰservlet����Ӧ��·��
					item.write(new File(dir, System.currentTimeMillis()
							+ item.getName().substring(
									item.getName().lastIndexOf("."))));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 7
Source File: FessMultipartRequestHandler.java    From fess with Apache License 2.0 5 votes vote down vote up
protected ServletFileUpload createServletFileUpload(final HttpServletRequest request) {
    final DiskFileItemFactory fileItemFactory = createDiskFileItemFactory();
    final ServletFileUpload upload = newServletFileUpload(fileItemFactory);
    upload.setHeaderEncoding(request.getCharacterEncoding());
    upload.setSizeMax(getSizeMax());
    return upload;
}
 
Example 8
Source File: Uploader.java    From jeecg with Apache License 2.0 5 votes vote down vote up
private void parseParams() {

		DiskFileItemFactory dff = new DiskFileItemFactory();
		try {
			ServletFileUpload sfu = new ServletFileUpload(dff);
			sfu.setSizeMax(this.maxSize);
			sfu.setHeaderEncoding(Uploader.ENCODEING);

			FileItemIterator fii = sfu.getItemIterator(this.request);

			while (fii.hasNext()) {
				FileItemStream item = fii.next();
				// 普通参数存储
				if (item.isFormField()) {

					this.params.put(item.getFieldName(),
							this.getParameterValue(item.openStream()));

				} else {

					// 只保留一个
					if (this.inputStream == null) {
						this.inputStream = item.openStream();
						this.originalName = item.getName();
						return;
					}

				}

			}

		} catch (Exception e) {
			this.state = this.errorInfo.get("UNKNOWN");
		}

	}
 
Example 9
Source File: UploadUtils.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
/**
	 * 处理上传内容
	 * 
	 * @param request
	 * @param maxSize
	 * @return
	 */
//	@SuppressWarnings("unchecked")
	private Map<String, Object> initFields(HttpServletRequest request) {

		// 存储表单字段和非表单字段
		Map<String, Object> map = new HashMap<String, Object>();

		// 第一步:判断request
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		// 第二步:解析request
		if (isMultipart) {
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// 阀值,超过这个值才会写到临时目录,否则在内存中
			factory.setSizeThreshold(1024 * 1024 * 10);
			factory.setRepository(new File(tempPath));

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			upload.setHeaderEncoding("UTF-8");

			// 最大上传限制
			upload.setSizeMax(maxSize);

			/* FileItem */
			List<FileItem> items = null;
			// Parse the request
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// 第3步:处理uploaded items
			if (items != null && items.size() > 0) {
				Iterator<FileItem> iter = items.iterator();
				// 文件域对象
				List<FileItem> list = new ArrayList<FileItem>();
				// 表单字段
				Map<String, String> fields = new HashMap<String, String>();
				while (iter.hasNext()) {
					FileItem item = iter.next();
					// 处理所有表单元素和文件域表单元素
					if (item.isFormField()) { // 表单元素
						String name = item.getFieldName();
						String value = item.getString();
						fields.put(name, value);
					} else { // 文件域表单元素
						list.add(item);
					}
				}
				map.put(FORM_FIELDS, fields);
				map.put(FILE_FIELDS, list);
			}
		}
		return map;
	}
 
Example 10
Source File: UploadUtils.java    From jeewx with Apache License 2.0 4 votes vote down vote up
/**
 * 处理上传内容
 * 
 * @param request
 * @param maxSize
 * @return
 */
@SuppressWarnings("unchecked")
private Map<String, Object> initFields(HttpServletRequest request) {

	// 存储表单字段和非表单字段
	Map<String, Object> map = new HashMap<String, Object>();

	// 第一步:判断request
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	// 第二步:解析request
	if (isMultipart) {
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 阀值,超过这个值才会写到临时目录,否则在内存中
		factory.setSizeThreshold(1024 * 1024 * 10);
		factory.setRepository(new File(tempPath));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		upload.setHeaderEncoding("UTF-8");

		// 最大上传限制
		upload.setSizeMax(maxSize);

		/* FileItem */
		List<FileItem> items = null;
		// Parse the request
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 第3步:处理uploaded items
		if (items != null && items.size() > 0) {
			Iterator<FileItem> iter = items.iterator();
			// 文件域对象
			List<FileItem> list = new ArrayList<FileItem>();
			// 表单字段
			Map<String, String> fields = new HashMap<String, String>();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				// 处理所有表单元素和文件域表单元素
				if (item.isFormField()) { // 表单元素
					String name = item.getFieldName();
					String value = item.getString();
					fields.put(name, value);
				} else { // 文件域表单元素
					list.add(item);
				}
			}
			map.put(FORM_FIELDS, fields);
			map.put(FILE_FIELDS, list);
		}
	}
	return map;
}
 
Example 11
Source File: FileUploadUtils.java    From TinyMooc with Apache License 2.0 4 votes vote down vote up
public static final HashMap UploadFile(HttpServletRequest request, HttpServletResponse response, String filepaths) throws Exception {
    HashMap params = new HashMap();
    String pathType = "images";
    if (!(filepaths.equals("")))
        pathType = filepaths;
    String readPath = "";
    String contextPath = "";
    if ((readPath == null) || (readPath.equals("")))
        readPath = request.getSession().getServletContext().getRealPath("");

    if ((contextPath == null) || (contextPath.equals("")))
        contextPath = request.getContextPath();

    String savePhotoPath = mkdirFile(readPath, pathType, true);
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory dff = new DiskFileItemFactory();
        dff.setSizeThreshold(1024000);
        ServletFileUpload sfu = new ServletFileUpload(dff);
        List fileItems = sfu.parseRequest(request);
        sfu.setFileSizeMax(5000000L);
        sfu.setSizeMax(10000000L);
        sfu.setHeaderEncoding("UTF-8");
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = new String(item.getString().getBytes(
                        "ISO8859-1"), "utf-8");
                params.put(name, value);
            } else if ((item.getSize() > 0L) &&
                    (item.getName() != null)) {
                File fullFile = new File(item.getName());
                File fileOnServer = new File(savePhotoPath,
                        fullFile.getName());
                item.write(fileOnServer);
                String fileName2 = fileOnServer.getName();
                String fileType = fileName2.substring(fileName2
                        .lastIndexOf("."));
                String filepath = savePhotoPath + "/" +
                        new Date().getTime() + fileType;
                File newFile = new File(filepath);
                fileOnServer.renameTo(newFile);
                String returnString = filepath.substring(readPath
                        .length());
                params.put(item.getFieldName(), request.getRequestURL().toString().replace(request.getRequestURI(), "") + contextPath +
                        returnString);
            }
        }
    }

    return params;
}
 
Example 12
Source File: FileController.java    From cms with Apache License 2.0 4 votes vote down vote up
public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException
  {
org.json.JSONObject returnJson = new org.json.JSONObject();
WPBAuthenticationResult authenticationResult = this.handleAuthentication(request);
if (! isRequestAuthenticated(authenticationResult))
{
	httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null, authenticationResult);
	return ;
}

      try
      {
            ServletFileUpload upload = new ServletFileUpload();
            upload.setHeaderEncoding("UTF-8");
            FileItemIterator iterator = upload.getItemIterator(request);
            WPBFile ownerFile = null;
            Map<String, WPBFile> subfolderFiles = new HashMap<String, WPBFile>();
            
            while (iterator.hasNext()) {
              FileItemStream item = iterator.next();
             
              if (item.isFormField() && item.getFieldName().equals("ownerExtKey"))
              {
                  String ownerExtKey = Streams.asString(item.openStream());
                  ownerFile = getDirectory(ownerExtKey, adminStorage);	            
              } else
              if (!item.isFormField() && item.getFieldName().equals("file")) {
                
                String fullName = item.getName();
                String directoryPath = getDirectoryFromLongName(fullName);
                String fileName = getFileNameFromLongName(fullName);
                
                Map<String, WPBFile> tempSubFolders = checkAndCreateSubDirectory(directoryPath, ownerFile);
                subfolderFiles.putAll(tempSubFolders);
                
                // delete the existing file
                WPBFile existingFile = getFileFromDirectory(subfolderFiles.get(directoryPath) , fileName);
                if (existingFile != null)
                {
                    deleteFile(existingFile, 0);
                }
                
                // create the file
                WPBFile file = new WPBFile();
                file.setExternalKey(adminStorage.getUniqueId());
                file.setFileName(fileName);
                file.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
                file.setDirectoryFlag(0);
                
                addFileToDirectory(subfolderFiles.get(directoryPath), file, item.openStream());
                
              }
            } 
            
            returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null));           
               httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null, authenticationResult);
      } catch (Exception e)
      {
          Map<String, String> errors = new HashMap<String, String>();     
          errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD);
          httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors);          
      }
  }
 
Example 13
Source File: HttpSupport.java    From javalite with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a collection of uploaded files and form fields from a multi-part request.
 * This method uses <a href="http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html">DiskFileItemFactory</a>.
 * As a result, it is recommended to add the following to your web.xml file:
 *
 * <pre>
 *   &lt;listener&gt;
 *      &lt;listener-class&gt;
 *         org.apache.commons.fileupload.servlet.FileCleanerCleanup
 *      &lt;/listener-class&gt;
 *   &lt;/listener&gt;
 *</pre>
 *
 * For more information, see: <a href="http://commons.apache.org/proper/commons-fileupload/using.html">Using FileUpload</a>
 *
 * @param encoding specifies the character encoding to be used when reading the headers of individual part.
 * When not specified, or null, the request encoding is used. If that is also not specified, or null,
 * the platform default encoding is used.
 *
 * @param maxUploadSize maximum size of the upload in bytes. A value of -1 indicates no maximum.
 *
 * @return a collection of uploaded files from a multi-part request.
 */
protected List<FormItem> multipartFormItems(String encoding, long maxUploadSize) {
    //we are thread safe, because controllers are pinned to a thread and discarded after each request.
    if(RequestContext.getFormItems() != null ){
        return RequestContext.getFormItems();
    }

    HttpServletRequest req = RequestContext.getHttpRequest();

    if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload.
        RequestContext.setFormItems(((AWMockMultipartHttpServletRequest) req).getFormItems());
    } else {

        if (!ServletFileUpload.isMultipartContent(req))
            throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ...");

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(Configuration.getMaxUploadSize());
        factory.setRepository(Configuration.getTmpDir());

        ServletFileUpload upload = new ServletFileUpload(factory);
        if(encoding != null)
            upload.setHeaderEncoding(encoding);
        upload.setFileSizeMax(maxUploadSize);
        try {
            List<org.apache.commons.fileupload.FileItem> apacheFileItems = upload.parseRequest(RequestContext.getHttpRequest());
            ArrayList items = new ArrayList<>();
            for (FileItem apacheItem : apacheFileItems) {
                ApacheFileItemFacade f = new ApacheFileItemFacade(apacheItem);
                if(f.isFormField()){
                    items.add(new FormItem(f));
                }else{
                    items.add(new org.javalite.activeweb.FileItem(f));
                }
            }
            RequestContext.setFormItems(items);
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }
    return RequestContext.getFormItems();
}
 
Example 14
Source File: UploadUtils.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 处理上传内容
 * 
 * @param request
 * @param maxSize
 * @return
 */
@SuppressWarnings("unchecked")
private Map<String, Object> initFields(HttpServletRequest request) {

	// 存储表单字段和非表单字段
	Map<String, Object> map = new HashMap<String, Object>();

	// 第一步:判断request
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	// 第二步:解析request
	if (isMultipart) {
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 阀值,超过这个值才会写到临时目录,否则在内存中
		factory.setSizeThreshold(1024 * 1024 * 10);
		factory.setRepository(new File(tempPath));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		upload.setHeaderEncoding("UTF-8");

		// 最大上传限制
		upload.setSizeMax(maxSize);

		/* FileItem */
		List<FileItem> items = null;
		// Parse the request
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 第3步:处理uploaded items
		if (items != null && items.size() > 0) {
			Iterator<FileItem> iter = items.iterator();
			// 文件域对象
			List<FileItem> list = new ArrayList<FileItem>();
			// 表单字段
			Map<String, String> fields = new HashMap<String, String>();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				// 处理所有表单元素和文件域表单元素
				if (item.isFormField()) { // 表单元素
					String name = item.getFieldName();
					String value = item.getString();
					fields.put(name, value);
				} else { // 文件域表单元素
					list.add(item);
				}
			}
			map.put(FORM_FIELDS, fields);
			map.put(FILE_FIELDS, list);
		}
	}
	return map;
}