📄 multipartrequest.java
字号:
package test;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.util.Streams;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class MultipartRequest extends HttpServletRequestWrapper {
HashMap parameters = new HashMap();
HashMap files = new HashMap();
public MultipartRequest(HttpServletRequest request)
throws FileUploadException, IOException {
super(request);
DiskFileItemFactory dff = new DiskFileItemFactory();
dff.setSizeThreshold(1024 * 1024); // 内存最多存储1MB数据,超过就用临时目录缓存
ServletFileUpload sfu = new ServletFileUpload(dff);
sfu.setSizeMax(1024 * 1024 * 10); // 最多上传10MB数据
sfu.setHeaderEncoding("utf-8");
FileItemIterator fii = sfu.getItemIterator(request);
while (fii.hasNext()) {
FileItemStream fis = fii.next();
if (fis.isFormField()) {
InputStream stream = fis.openStream();
String fieldName = fis.getFieldName();
String content = null;
content = Streams.asString(stream, "utf-8");
setParameter(fieldName, content);
} else {
String pathSrc = fis.getName();
if (pathSrc.trim().equals("")) {
continue;
}
String fieldName = fis.getFieldName();
files.put(fieldName, fis);
}
}
}
private void setParameter(String fieldName, String content) {
String[] mValue = (String[]) parameters.get(fieldName);
if (mValue == null) {
mValue = new String[0];
}
String[] newValue = new String[mValue.length + 1];
System.arraycopy(mValue, 0, newValue, 0, mValue.length);
newValue[mValue.length] = content;
parameters.put(fieldName, newValue);
}
public String getParameter(String name) {
String[] mValue = (String[]) parameters.get(name);
if ((mValue != null) && (mValue.length > 0)) {
return mValue[0];
}
return null;
}
public Enumeration getParameterNames() {
Collection c = parameters.keySet();
return Collections.enumeration(c);
}
public String[] getParameterValues(String name) {
String[] mValue = (String[]) parameters.get(name);
return mValue;
}
public Map getParameterMap() {
return parameters;
}
public FileItemStream getFileItem(String name) {
FileItemStream fItem = (FileItemStream) files.get(name);
return fItem;
}
public Enumeration getFileItemNames() {
Collection c = files.keySet();
return Collections.enumeration(c);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -