org.smart4j.framework.mvc.UploadHelper Maven / Gradle / Ivy
package org.smart4j.framework.mvc;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.mvc.bean.Multipart;
import org.smart4j.framework.mvc.bean.Multiparts;
import org.smart4j.framework.mvc.bean.Params;
import org.smart4j.framework.mvc.fault.UploadException;
import org.smart4j.framework.util.FileUtil;
import org.smart4j.framework.util.StreamUtil;
import org.smart4j.framework.util.StringUtil;
/**
* 封装文件上传相关操作
*
* @author huangyong
* @since 2.1
*/
public class UploadHelper {
private static final Logger logger = LoggerFactory.getLogger(UploadHelper.class);
/**
* FileUpload 对象(用于解析所上传的文件)
*/
private static ServletFileUpload fileUpload;
/**
* 初始化
*/
public static void init(ServletContext servletContext) {
// 获取一个临时目录(使用 Tomcat 的 work 目录)
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
logger.debug("[Smart] temp dir of uploading: {}", repository);
// 创建 FileUpload 对象
fileUpload = new ServletFileUpload(new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
// 设置上传限制
int uploadLimit = FrameworkConstant.UPLOAD_LIMIT;
if (uploadLimit != 0) {
fileUpload.setFileSizeMax(uploadLimit * 1024 * 1024); // 单位为 M
logger.debug("[Smart] limit of uploading: {}M", uploadLimit);
}
}
/**
* 判断请求是否为 multipart 类型
*/
public static boolean isMultipart(HttpServletRequest request) {
// 判断上传文件的内容是否为 multipart 类型
return ServletFileUpload.isMultipartContent(request);
}
/**
* 创建 multipart 请求参数列表
*/
public static List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy