解决当FORM的ENCTYPE="multipart/form-data" 时request.getParameter()获取不到值的方法
url:http://blog.csdn.net/georgejin/archive/2007/07/25/1706647.aspx
今天在原来上传文件页面的基础上,想添加一段文件的简介
因为同时要上传文件,所以ENCTYPE="multipart/form-data" 必须要加在form里面
可是这样的话,我再servlet里面用request.getParameter()方法无论如何都只是获得null值,
不是一般的郁闷,百度了一下,有人出现了同样的问题可是它用的是jspsmartupload组件实现文件上传的,
而我用的commons fileupload组件,仔细看了一下这个组件的api,可是英语太差了,没有发现相关的信息
我又尝试用session传递参数,可是发现有点麻烦,因为在表单提交之时你就得赋给session表单上它的数值,
这似乎要javascript,可是偶也不会,
后来只有google了,搜索了一些中文网页,也没有找到资料,试试不限制语言,呵呵呵,一大片,后来被俺发
现了这个
I cannot read the submitter using request.getParameter("submitter") (it returns null). ]
Situation:javax.servlet.HttpServletRequest.getParameter(String) returns null when the ContentType is multipart/form-data
Solutions:
Solution A:1. download http://www.servlets.com/cos/index.html2 . invoke getParameters() on com.oreilly.servlet.MultipartRequest
Solution B:1. download http://jakarta.apache.org/commons/sandbox/fileupload/2 . invoke readHeaders() in org.apache.commons.fileupload.MultipartStream
Solution C:1. download http://users.boone.net/wbrameld/multipartformdata/2 . invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData
Solution D:Use Struts. Struts 1.1 handles this automatically.说是不详细,接着往下看,另一种解决方法>
Solution B:
> 1. download > http://jakarta.apache.org/commons/sandbox/fileupload/
> 2. invoke readHeaders() in
> org.apache.commons.fileupload.MultipartStream
The Solution B as given by my dear friend is a bit hectic and a bit complex :(
We can try the following solution which I found much simpler (at least in usage).
1. Download one of the versions of UploadFile from http://jakarta.apache.org/commons/fileupload/
2. Invoke parseRequest(request) on org.apache.commons.fileupload.FileUploadBase which returns list of org.apache.commons.fileupload.FileItem objects.
3. Invoke isFormField() on each of the FileItem objects. This determines whether the file item is a form paramater or stream of uploaded file.
4. Invoke getFieldName() to get parameter name and getString() to get parameter value on FileItem if it's a form parameter. Invoke write(java.io.File) on FileItem to save the uploaded file stream to a file if the FileItem is not a form parameter.
还有一种方法就是使用jspsmartupload表单中enctype="multipart/form-data"的意思,是设置 表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了 multipart/form-data,才能完整的传递文件数据
但是设置了 enctype="multipart/form-data" ,除了file类型表单能获取到,其他value通过request.getParameter都得不到。这种情况下我们可以利用组件来解决该问题,例如用 jspsmartupload组件
com.jspsmart.upload.SmartUpload su = new com.jspsmart.upload.SmartUpload();
su.initialize(pageContext);
su.service(request, response);
su.setTotalMaxFileSize(100000000);
su.setAllowedFilesList("zip,rar");
su.setDeniedFilesList("exe,bat,jsp,htm,html,,");
su.upload();
String Name = su.getRequest().getParameter("Name");
String TYPE_ID = su.getRequest().getParameter("Type");
通过 su.getRequest().getParameter("value");就可以了,su.upload()好象必须放在前面,测试中将su.upload()放在获取参数后面不成功。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/georgejin/archive/2007/07/25/1706647.aspx
关于用jspSmartUpload控件上传文件并附带参数的吐血体验
url:http://blog.csdn.net/thinker28754/archive/2007/05/26/1626844.aspx
用于上传数据的表单:
提交的后台的servlet
SmartUpload su =new SmartUpload();
su.initialize(this.getServletConfig(), request, response);
String realPath = this.getServletContext().getRealPath("");
String path=realPath+"/images";
su.setAllowedFilesList("gif,jpg");
su.upload();
int count=su.save(path);
msdnid=su.getRequest().getParameter("phone");//注意这是接收表单传过来的参数
System.out.println("msdnid="+msdnid);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
特别说明:用于接收表单参数的语句一定要放在su.upload();语句的后面,也就是说要在文件上传后再接收,否则
不管你怎么试接收到的结果总是"null".
这是我在苦苦试了一天在晕到前的2分钟试出来的,真的不容易呀!!!!!
在上述问题得到解决后,当所传的参数为汉字时则接收到的全是乱码,经过反复实验将表单页面的编码格式设成"gb2312"就解决了这个问题.
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/thinker28754/archive/2007/05/26/1626844.aspx
解决当FORM的ENCTYPE="multipart/form-data" 时获取不到其它参数值的方法 ?
url:http://blog.csdn.net/heitu278/archive/2008/09/04/2882346.aspx
前提:使用 commons-fileupload-1.1.jar
UploadListener listener = new UploadListener(request, 0);
// Create a factory for disk-based file items
FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// process uploads ..
List fileItems=upload.parseRequest(request);
Iterator iter = fileItems.iterator(); // 依次处理每个控件
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();// 忽略其他是文件域的所有表单信息
if (item.isFormField()){
out.println(item.getFieldName()+"="+item.getString()); 获得表单数据
}
}
}catch (FileUploadException e){
e.printStackTrace();
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/heitu278/archive/2008/09/04/2882346.aspx
表单form的enctype="multipart/form-data"使用体会 收藏
在使用表单传送数据的时候,如果form 加了enctype="multipart/form-data" 这个属性,那么表单请求传到另一个jsp或servlet 里时
是不能用request.getParameter()来获取到各个表单元素的值的。
可以通用这样(上传组件提供的API):
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
org.apache.commons.fileupload.FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) iter
.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("GBK");
//out.println(name + "=" + value);
params.put(name.toUpperCase(), value.trim());
} ......
===============================================================================
使用multipart/form-data上传时,发送的请求和一般的http不一样,需要转化后才能读其他参数。
如果你用spring,它提供一个MultiRequestResolver,只需要:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
然后就能正常读取参数:
multipartRequest.getParameter("xxx");
以下是spring的处理方法,必须首先安装commons-fileupload组件:
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
DiskFileUpload fileUpload = this.fileUpload;
String enc = determineEncoding(request);
// use prototype FileUpload instance if the request specifies
// its own encoding that does not match the default encoding
if (!enc.equals(this.defaultEncoding)) {
fileUpload = new DiskFileUpload();
fileUpload.setSizeMax(this.fileUpload.getSizeMax());
fileUpload.setSizeThreshold(this.fileUpload.getSizeThreshold());
fileUpload.setRepositoryPath(this.fileUpload.getRepositoryPath());
fileUpload.setHeaderEncoding(enc);
}
try {
List fileItems = fileUpload.parseRequest(request);
Map parameters = new HashMap();
Map multipartFiles = new HashMap();
for (Iterator it = fileItems.iterator(); it.hasNext();) {
FileItem fileItem = (FileItem) it.next();
if (fileItem.isFormField()) {
String value = null;
try {
value = fileItem.getString(enc);
}
catch (UnsupportedEncodingException ex) {
logger.warn("Could not decode multipart item '" + fileItem.getFieldName() +
"' with encoding '" + enc + "': using platform default");
value = fileItem.getString();
}
String[] curParam = (String[]) parameters.get(fileItem.getFieldName());
if (curParam == null) {
// simple form field
parameters.put(fileItem.getFieldName(), new String[] { value });
}
else {
// array of simple form fields
String[] newParam = StringUtils.addStringToArray(curParam, value);
parameters.put(fileItem.getFieldName(), newParam);
}
}
else {
// multipart file field
CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
multipartFiles.put(file.getName(), file);
if (logger.isDebugEnabled()) {
logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() +
" bytes with original filename [" + file.getOriginalFilename() + "], stored " +
file.getStorageDescription());
}
}
}
/***** 注意 parameters 就是普通的text之类的字段的值 *****/
return new DefaultMultipartHttpServletRequest(request, multipartFiles, parameters);
}
catch (FileUploadBase.SizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(this.fileUpload.getSizeMax(), ex);
}
catch (FileUploadException ex) {
throw new MultipartException("Could not parse multipart request", ex);
}
}
====================================================================================================