All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.yydf.struts.wrapper.MultipartRequestWrapper Maven / Gradle / Ivy

There is a newer version: 1.0.2
Show newest version
package com.github.yydf.struts.wrapper;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.util.Streams;

import com.github.yydf.struts.mapper.MultipartFile;

/**
 * 解析Multipart请求
 * 
 * @author YYDF
 *
 */
public class MultipartRequestWrapper {

	private HttpServletRequest request;
	private ServletContext ctx;
	private final HashMap paras = new HashMap<>();
	private final HashMap multipartFiles = new HashMap<>();

	public MultipartRequestWrapper(HttpServletRequest req) {
		this.request = req;
		this.ctx = req.getServletContext();
	}

	public void processRequest(processFile process) {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			FileItemIterator items = upload.getItemIterator(request);
			if (items != null) {
				while (items.hasNext()) {
					FileItemStream stream = items.next();
					if (stream.isFormField())
						paras.put(stream.getFieldName(), Streams.asString(stream.openStream(), "utf-8"));
					else {
						MultipartFile file = new MultipartFile(stream);
						paras.put(file.getFieldName(), process.processMultipartFile(file));
						multipartFiles.put(file.getFieldName(), file);
					}
				}
			}
		} catch (FileUploadException | IOException e) {
			ctx.log("Process request faild", e);
		}
	}

	public String getField(String name) {
		String str = paras.get(name);
		if (str == null)
			str = request.getParameter(name);
		return str;
	}

	public MultipartFile getMultipartFile(String name) {
		return multipartFiles.get(name);
	}

	public void clear() {
		paras.clear();
		for (MultipartFile file : multipartFiles.values()) {
			file.clear();
		}
		multipartFiles.clear();
		request = null;
		ctx = null;
	}

	public interface processFile {
		String processMultipartFile(MultipartFile file);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy