com.github.hetianyi.common.http.FileUploadHandler Maven / Gradle / Ivy
package com.github.hetianyi.common.http;
import com.github.hetianyi.common.fun.Function30;
import com.google.common.io.ByteStreams;
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.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.BiConsumer;
/**
* 文件上传工具类
*
* @author Jason He
* @version 1.0.0
* @date 2019-12-28
*/
public class FileUploadHandler {
private static final Logger log = LoggerFactory.getLogger(FileUploadHandler.class);
private HttpServletRequest request;
private Function30 fileFieldProcessor;
private BiConsumer formFieldProcessor;
public FileUploadHandler(HttpServletRequest request) {
this.request = request;
}
/**
* 定义文本域处理器
* @param processor
* @return
*/
public FileUploadHandler onFormField(BiConsumer processor) {
this.formFieldProcessor = processor;
return this;
}
/**
* 定义文件域处理器
* @param processor
* @return
*/
public FileUploadHandler onFileField(Function30 processor) {
this.fileFieldProcessor = processor;
return this;
}
/**
* 开始处理文件上传
* @throws IOException
* @throws FileUploadException
*/
public void process() throws Exception {
// 拒绝非文件表单
if (!ServletFileUpload.isMultipartContent(request)) {
log.error("the request contains no multipart content.");
throw new IllegalStateException("the request contains no multipart content.");
}
ServletFileUpload fileUpload = new ServletFileUpload();
FileItemIterator iterator = fileUpload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
String name = item.getFieldName();
InputStream is = null;
try {
is = item.openStream();
// 处理文本域
if (item.isFormField()) {
String fieldValue = new String(ByteStreams.toByteArray(is));
if (log.isDebugEnabled()) {
log.debug("form field: {} => {}", name, fieldValue);
}
formFieldProcessor.accept(name, fieldValue);
} else {
// 处理文件
String fileName = item.getName();
if (log.isDebugEnabled()) {
log.debug("file field: {} => {}", name, fileName);
}
fileFieldProcessor.accept(name, fileName, is);
}
} catch (IOException e) {
throw e;
} finally {
if (null != is) {
is.close();
}
}
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy