天天看點

webwork2檔案上傳

       項目是ssh的,有個功能是檔案上傳,檔案上傳以前也做過,不過很久了,記憶模糊了。。。。嘿嘿,自己給自己找理由,跑題啦!

       上傳功能對應的action配置fileUpload攔截器,而我又習慣性的加入了common-fileupload.jar,想用它來實作檔案上傳,AttachUpLoadAction代碼片段如下

request = ServletActionContext.getRequest();
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		DiskFileItemFactory factory = new DiskFileItemFactory();   
//		 當檔案大小超過300k時,就在磁盤上建立臨時檔案   
		factory.setSizeThreshold(300000);   
		//設計檔案上傳的臨時目錄   
		factory.setRepository(new File("D:\\temp"));   
		ServletFileUpload upload = new ServletFileUpload(factory);   
		// 檔案大小不能超過10M   
		upload.setSizeMax(10000000);
//		 Parse the request
		List items = upload.parseRequest(request);
//		upload.setProgressListener(new ProgressListener());
		System.out.println("#####################items.size()=="+items.size());
           

        開始不知道為什麼,items.size()一直為0,而通過request.getParameter("meetingId")取得一個text類型的input框參數,則可以取到,而boolean isMultipart = ServletFileUpload.isMultipartContent(request);

傳回的也是true,為什麼size還是0呢?

      在查閱了webwork api中關于FileUploadInterceptor的部分内容以及http://commons.apache.org/fileupload/faq.html内容後,問題解決了,是這麼說的。

Why is parseRequest() returning no items?

This most commonly happens when the request has already been parsed, or processed in some other way. Since the input stream has aleady been consumed by that earlier process, it is no longer available for parsing by Commons FileUpload.

I'm using FileUpload in an Action, but it's not working. Why?

Struts recognises multipart requests, and parses them automatically, presenting the request parameters to your code in the same manner as if they were regular request parameters. Since Struts has already processed the request, and made it available in your form bean, the input stream is no longer available for parsing, so attempting to do so with FileUpload will fail.

But I need to parse the request myself. How can I do that?

Struts parses multipart a request as a part of the process of populating your form bean from that request. If, for some reason, you need to have full control over the multipart parsing, you can do so by configuring your action mapping without an associated form bean. (A better way of doing this, however, is to replace the default multipart handler with your own. See the Struts documentation for details.)

針對第一個問題的解釋,可我還是有點疑問,雖說webwork2通過對request等對象進行了解耦,可以不依賴容器進行測試,但是我們知道action中也是可以通過request = ServletActionContext.getRequest();取得request 等對象,直接進行操作的嗎?為什麼request.getParameter("meetingId")可以得到元素,而  List items = upload.parseRequest(request)不行呢?高人來解釋啊( 這段話我說的有點亂,表達能力太差啦)