2011-12-13 44 views
1

我正在使用wicket將大型(〜2Gb +)zip文件提交給一個web應用程序,以處理zip文件我正在使用java.util.zip。*類,而且我需要能夠從zip文件中讀取隨機條目。所以,我的代碼是這樣的:Wicket FileUploadField和大型zip上傳

class MyForm extends Form { 
    private FileUploadField fileField; 

    MyForm(String id) { 
     super(id); 
     fileField = new FileUploadField("upload"); 
     add(fileField); 
    } 

    @Override 
    protected void onSubmit() { 
     FileUpload fileUpload = fileField.getFileUpload(); 
     File file = fileUpload.writeToTempFile(); 
     ZipFile zipFile = new ZipFile(file); 
     // Do more stuff 
    } 
} 

由於上傳的解析請求時大檢票口把它放在一個臨時文件,但隨後writeToTempFile()將其複製到另一個臨時文件,所以我現在有兩個副本的磁盤上的文件。這浪費了磁盤空間,磁盤IO並增加了請求處理時間。

我不能使用ZipFileInputStream,因爲我需要隨機訪問文件。有沒有辦法阻止wicket複製磁盤上的文件?

回答

1

是的,但這不是一個好方法。

您可以繼承FileUploadField,並覆蓋getFileUpload()方法,並使用一個副本公開FileItem

或者,另一種方式是在你的FileUploadField子類來創建一個新的方法只是返回FileItem

public FileItem getFileItem() { 
    return ((IMultipartWebRequest)getRequest()).getFile(getInputName()); 
} 
+0

謝謝。爲了完成這個,FileItem仍然不允許你訪問文件,實現FileItem的DiskFileItem具有getStoreLocation()方法,因此可以進行測試和強制轉換。 – 2011-12-14 09:14:54

2

大廈從@biziclop答案我寫了這個類:

public class RawFileUploadField extends FileUploadField { 

private static final long serialVersionUID = 1L; 

public RawFileUploadField(String id) { 
    super(id); 
} 

/** 
* Attempts to get the file that is on disk if it exists and if it doesn't 
* then just write the file to a temp location. 
* @return The file or <code>null</code> if no file. 
* @throws IOException 
*/ 
public File getFile() throws IOException { 
    // Get request 
    final Request request = getRequest(); 

    // If we successfully installed a multipart request 
    if (request instanceof IMultipartWebRequest) 
    { 
     // Get the item for the path 
     FileItem item = ((IMultipartWebRequest)request).getFile(getInputName()); 
     if (item instanceof DiskFileItem) { 
      File location = ((DiskFileItem)item).getStoreLocation(); 
      if (location != null) { 
       return location; 
      } 
     } 
    } 
    // Fallback 
    FileUpload upload = getFileUpload(); 
    return (upload != null)?upload.writeToTempFile():null; 
    } 

}