手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>程序设计>Java技术>列表

解决当FORM的ENCTYPE="multipart/form-data" 时request.getParameter()获取不到值的方

来源:互联网 作者:west263.com 时间:2008-02-23
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

今天在原来上传文件页面的基础上,想添加一段文件的简介

因为同时要上传文件,所以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.html

2. 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.

按照上面的步骤来,果然一切都ok,GOOGLE真不错,主要是getFieldName和getString,
虽然说这种做法有一点麻烦,但稍微判断加工一下,总比获取不到强

上一篇: Controller 接口及其实现
下一篇: 如何使用Java编写多线程程序

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!