2015年9月7日 星期一

在 Grails 下,使用 Apache FileUpload

我不曉得在台灣有多少人在用 Grails,其中是否有人也碰到類似的問題。還是稍微記一下,供可能碰到同樣問題的人參考。

在 Grails 下,自行建立的 Servelet 中,使用 Apache FileUpload 處理上傳檔案,程式碼大致如下

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List /* FileItem */ items = upload.parseRequest(request);

不論怎麼試,所傳回的 items 一直都是空的。

好不容易,才找到問題所在,因為 Grails 會在預先處理 request 的資料。因此要修正 config.groovy,將 disable 處理 multi part requests 的設定設為 true
// whether to disable processing of multi part requests
// grails.web.disable.multipart=false
grails.web.disable.multipart=true

原因,依據 Apache's FAQ page for FileUpload 中的說明,"A Request can only be parsed once."

Question: Why is parseRequest() returning no items?
Answer: "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."


沒有留言:

張貼留言

網誌存檔