?? multipartrequest.java
字號:
package org.it315;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
public class MultipartRequest extends HttpServletRequestWrapper
{
HashMap parameters = new HashMap();
HashMap files = new HashMap();
public MultipartRequest(HttpServletRequest request)
throws FileUploadException
{
super(request);
DiskFileUpload fu = new DiskFileUpload();
//最多上傳200M數據
fu.setSizeMax(1024 * 1024 * 200);
//超過1M的字段數據采用臨時文件緩存
fu.setSizeThreshold(1024 * 1024);
//采用默認的臨時文件存儲位置
//fu.setRepositoryPath(...);
//設置上傳的普通字段內容和文件字段的文件名所采用的字符集編碼
fu.setHeaderEncoding("gb2312");
//得到所有表單字段對象的集合
List fileItems = null;
//如果解析數據時出現問題,直接將FileUploadException外拋
fileItems = fu.parseRequest(request);
//處理每個表單字段
Iterator i = fileItems.iterator();
while (i.hasNext())
{
FileItem fi = (FileItem) i.next();
if (fi.isFormField())
{
String fieldName = fi.getFieldName();
String content = null;
try
{
content = fi.getString("GB2312");
}
catch(Exception e){}
setParameter(fieldName,content);
}
else
{
String pathSrc = fi.getName();
/*如果用戶沒有在FORM表單的文件字段中選擇任何文件,
那么忽略對該字段項的處理*/
if(pathSrc.trim().equals(""))
{
continue;
}
String fieldName = fi.getFieldName();
files.put(fieldName,fi);
}
}
}
/**
* 向集合中添加一個參數,主要是考慮多個同名字段的情況。
*/
private void setParameter(String name, String value)
{
String[] mValue = (String[]) parameters.get(name);
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] = value;
parameters.put(name, 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 /*String*/ getParameterNames()
{
Collection c = parameters.keySet();
return Collections.enumeration(c);
}
/**
* 返回某個名稱所對應的所有參數值
*/
public String[] getParameterValues(String name)
{
String[] mValue = (String[]) parameters.get(name);
return mValue;
}
/**
* 返回包含所有參數名和對應的參數值的Map集合
*/
public Map getParameterMap()
{
return parameters;
}
/**
* 返回某個表單字段名所對應的FileItem對象
*/
public FileItem getFileItem(String name)
{
FileItem fItem = (FileItem)files.get(name);
return fItem;
}
/**
*返回所有上傳了文件的文件字段的名稱的集合
*/
public Enumeration /*String*/ getFileItemNames()
{
Collection c = files.keySet();
return Collections.enumeration(c);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -