支持 HTML5 和 Multipart 文件上传的 Java 处理类

package file;

import java.io.*;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

public class FileUploaderUtils {

	public static boolean supported(HttpServletRequest request) {
		String originalFilename = request.getHeader("content-disposition");
		if (originalFilename != null) return true;

		return ServletFileUpload.isMultipartContent(request);
	}

	public static HttpServletRequest asRequest(HttpServletRequest request, File uploadSavePath) {
		try {
			String originalFilename = request.getHeader("content-disposition");
			if (originalFilename != null) {
				return asHtml5Request(request, uploadSavePath);
			} else if (ServletFileUpload.isMultipartContent(request)) {
				return asMultipartRequest(request, uploadSavePath);
			}
			return request;
		} catch (RuntimeException e) {
			throw e;
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
	}

	// multipart/form-data
	private static FileUploaderRequest asMultipartRequest(HttpServletRequest request, File uploadSavePath) throws Throwable {
		FileUploaderRequest req = new FileUploaderRequest(request);

		ServletFileUpload upload = new ServletFileUpload();
		FileItemIterator it = upload.getItemIterator(request);
		while (it.hasNext()) {
			FileItemStream item = it.next();
			String fieldName = item.getFieldName();
			InputStream stream = item.openStream();
			if (item.isFormField()) {
				req.setParameter(fieldName, Streams.asString(stream));
			} else {
				String originalFilename = item.getName();
				File diskFile = new File(uploadSavePath, RandomStringUtils.randomAlphanumeric(16));

				OutputStream fos = new FileOutputStream(diskFile);
				IOUtils.copy(stream, fos);
				IOUtils.closeQuietly(fos);

				FileItem fileItem = new FileItem(fieldName, originalFilename, diskFile);
				req.setFile(fileItem.getFieldName(), fileItem);
			}
			IOUtils.closeQuietly(stream);
		}

		return req;
	}

	// application/octet-stream
	private static FileUploaderRequest asHtml5Request(HttpServletRequest request, File uploadSavePath) throws Throwable {
		String originalFilename = request.getHeader("content-disposition");
		if (originalFilename == null) {
			throw new ServletException("The request is not a html 5 file upload request.");
		}
		originalFilename = new String(originalFilename.getBytes("iso8859-1"), request.getCharacterEncoding());
		originalFilename = StringUtils.substringAfter(originalFilename, "; filename=");
		originalFilename = StringUtils.remove(originalFilename, "\"");
		originalFilename = URLDecoder.decode(originalFilename, "utf-8");

		File diskFile = new File(uploadSavePath, RandomStringUtils.randomAlphanumeric(16));

		InputStream fis = request.getInputStream();
		OutputStream fos = new FileOutputStream(diskFile);
		IOUtils.copy(fis, fos);
		IOUtils.closeQuietly(fis);
		IOUtils.closeQuietly(fos);

		FileUploaderRequest req = new FileUploaderRequest(request);
		FileItem fileItem = new FileItem("unknown", originalFilename, diskFile);
		req.setFile(fileItem.getFieldName(), fileItem);
		return req;
	}
}
package file;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * <p> This class functions as a wrapper around HttpServletRequest to provide
 * working getParameter methods for multipart requests. </p>
 * @see org.apache.struts.upload.MultipartRequestWrapper 
 */
public class FileUploaderRequest extends HttpServletRequestWrapper {
	private Map<String, String[]> parameters = new HashMap<String, String[]>();
	private Map<String, FileItem> files = new HashMap<String, FileItem>();

	public FileUploaderRequest(HttpServletRequest request) {
		super(request);
	}

	/**
	 * <p> Sets a parameter for this request.  The parameter is actually
	 * separate from the request parameters, but calling on the getParameter()
	 * methods of this class will work as if they weren't. </p>
	 */
	public void setParameter(String name, String value) {
		String[] values = (String[]) parameters.get(name);

		if (values == null) {
			values = new String[] { value };
			parameters.put(name, values);
		} else {
			String[] newValues = new String[values.length + 1];
			System.arraycopy(values, 0, newValues, 0, values.length);
			newValues[values.length] = value;
			parameters.put(name, newValues);
		}
	}

	/**
	 * <p> Attempts to get a parameter for this request.  It first looks in
	 * the underlying HttpServletRequest object for the parameter, and if that
	 * doesn't exist it looks for the parameters retrieved from the multipart
	 * request </p>
	 */
	@Override
	public String getParameter(String name) {
		String value = getRequest().getParameter(name);

		if (value == null) {
			String[] values = (String[]) parameters.get(name);
			if ((values != null) && (values.length > 0)) {
				value = values[0];
			}
		}

		return value;
	}

	/**
	 * <p> Returns the names of the parameters for this request. The
	 * enumeration consists of the normal request parameter names plus the
	 * parameters read from the multipart request </p>
	 */
	@Override
	public Enumeration<String> getParameterNames() {
		Enumeration<String> baseParams = getRequest().getParameterNames();
		List<String> list = new ArrayList<String>();

		while (baseParams.hasMoreElements()) {
			list.add(baseParams.nextElement());
		}

		Collection<String> multipartParams = parameters.keySet();
		Iterator<String> iterator = multipartParams.iterator();

		while (iterator.hasNext()) {
			list.add(iterator.next());
		}

		return Collections.enumeration(list);
	}

	/**
	 * <p> Returns the values of a parameter in this request. It first looks
	 * in the underlying HttpServletRequest object for the parameter, and if
	 * that doesn't exist it looks for the parameter retrieved from the
	 * multipart request. </p>
	 */
	@Override
	public String[] getParameterValues(String name) {
		String[] values = getRequest().getParameterValues(name);

		if (values == null) {
			values = (String[]) parameters.get(name);
		}

		return values;
	}

	/**
	 * <p> Combines the parameters stored here with those in the underlying
	 * request. If paramater values in the underlying request take precedence
	 * over those stored here. </p>
	 */
	@Override
	public Map<String, String[]> getParameterMap() {
		Map<String, String[]> map = new HashMap<String, String[]>(parameters);
		map.putAll(getRequest().getParameterMap());
		return map;
	}

	public void setFile(String name, FileItem file) {
		files.put(name, file);
	}

	public FileItem getFile(String name) {
		return files.get(name);
	}

	public Map<String, FileItem> getFiles() {
		return files;
	}
}
package file;

import java.io.*;
import org.apache.commons.io.*;

public class FileItem {
	protected final String fieldName;
	protected final String originalFileName;
	protected final String originalFileExt;
	protected final File diskFile;
	protected final long size;

	public FileItem(String fieldName, String originalFileName, File diskFile) {
		this.fieldName = fieldName;
		this.originalFileName = originalFileName;
		this.originalFileExt = FilenameUtils.getExtension(originalFileName);
		this.diskFile = diskFile;
		this.size = diskFile.length();
	}

	public String getFieldName() {
		return fieldName;
	}

	public String getOriginalFileName() {
		return originalFileName;
	}

	public String getOriginalFileExt() {
		return originalFileExt;
	}

	public File getDiskFile() {
		return diskFile;
	}

	public long getSize() {
		return size;
	}

	public void delete() {
		if (diskFile.exists()) {
			diskFile.delete();
		}
	}

	public void moveTo(File destFile) {
		try {
			FileUtils.moveFile(diskFile, destFile);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public void write(File destFile) {
		try {
			FileUtils.copyFile(diskFile, destFile);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public void write(OutputStream os) {
		try {
			IOUtils.copy(new FileInputStream(diskFile), os);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public InputStream asInputStream() {
		try {
			return new FileInputStream(diskFile);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	public String asString(String charset) {
		try {
			return FileUtils.readFileToString(diskFile, charset);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}


<?xml version="1.0" encoding="utf-8" ?>

<table display_name="文件">

    <column name="parent_id"
            type="ID"
            nullable="true"
            display_name="ParentID"
            />
    <column name="parent_type"
            type="varchar(50)"
            nullable="true"
            display_name="文件分类"
            />

    <column name="disk_file_name"
            type="varchar(250)"
            display_name="存储文件名"
            />

    <column name="original_file_name"
            type="varchar(250)"
            display_name="原始文件名"
            />

    <column name="destination_file_name"
            type="varchar(250)"
            display_name="显示文件名"
            />

    <column name="ext"
            type="varchar(10)"
            display_name="文件扩展名"
            />

    <column name="size"
            type="int"
            display_name="文件大小"
            />

    <column name="uploader_id"
            type="ID"
            display_name="上传用户姓名"
            />

    <column name="last_date" 
            type="datetime"	
            display_name="上传时间"
            />

</table>


你可能感兴趣的:(java,fileupload,multipart)