今天在原来上传文件页面的基础上,想添加一段文件的简介
因为同时要上传文件,所以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,
虽然说这种做法有一点麻烦,但稍微判断加工一下,总比获取不到强