Java Code Examples for org.apache.commons.fileupload.DiskFileUpload

The following examples show how to use org.apache.commons.fileupload.DiskFileUpload. These examples are extracted from open source projects. 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
@SuppressWarnings("all")
public UploadRequestWrapper(HttpServletRequest request) {

	super(request);

	// 判断是否为上传文件
	multipart = request.getHeader(MULTIPART_HEADER) != null
		&& request.getHeader(MULTIPART_HEADER).startsWith("multipart/form-data");

	if (multipart) {

		try {
			// 使用apache的工具解析
			DiskFileUpload upload = new DiskFileUpload();
			upload.setHeaderEncoding("utf8");

			// 解析,获得所有的文本域与文件域
			List<FileItem> fileItems = upload.parseRequest(request);

			for (Iterator<FileItem> it = fileItems.iterator(); it.hasNext(); ) {

				// 遍历
				FileItem item = it.next();
				if (item.isFormField()) {

					// 如果是文本域,直接放到map里
					params.put(item.getFieldName(), item.getString("utf8"));
				} else {

					// 否则,为文件,先获取文件名称
					String filename = item.getName().replace("\\", "/");
					filename = filename.substring(filename.lastIndexOf("/") + 1);

					// 保存到系统临时文件夹中
					File file = new File(System.getProperty("java.io.tmpdir"), filename);

					// 保存文件内容
					OutputStream ous = new FileOutputStream(file);
					ous.write(item.get());
					ous.close();

					// 放到map中
					params.put(item.getFieldName(), file);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}