今天在原來(lái)上傳文件頁(yè)面的基礎(chǔ)上,想添加一段文件的簡(jiǎn)介
因?yàn)橥瑫r(shí)要上傳文件,所以ENCTYPE="multipart/form-data" 必須要加在form里面
可是這樣的話,我再servlet里面用request.getParameter()方法無(wú)論如何都只是獲得null值,
不是一般的郁悶,百度了一下,有人出現(xiàn)了同樣的問(wèn)題可是它用的是jspsmartupload組件實(shí)現(xiàn)文件上傳的,
而我用的commons fileupload組件,仔細(xì)看了一下這個(gè)組件的api,可是英語(yǔ)太差了,沒(méi)有發(fā)現(xiàn)相關(guān)的信息
我又嘗試用session傳遞參數(shù),可是發(fā)現(xiàn)有點(diǎn)麻煩,因?yàn)樵诒韱翁峤恢畷r(shí)你就得賦給session表單上它的數(shù)值,
這似乎要javascript,可是偶也不會(huì),
后來(lái)只有g(shù)oogle了,搜索了一些中文網(wǎng)頁(yè),也沒(méi)有找到資料,試試不限制語(yǔ)言,呵呵呵,一大片,后來(lái)被俺發(fā)
現(xiàn)了這個(gè)
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.
說(shuō)是不詳細(xì),接著往下看,另一種解決方法
> 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.
按照上面的步驟來(lái),果然一切都o(jì)k,GOOGLE真不錯(cuò),主要是getFieldName和getString,
雖然說(shuō)這種做法有一點(diǎn)麻煩,但稍微判斷加工一下,總比獲取不到強(qiáng)