2011-06-09 118 views
1

我有一個要求,我需要爲不同情況允許不同的最大文件大小。示例:允許5 MB用於恢復,只有3 MB用於轉錄。如何使用Apache文件上傳使用情況根據文件名設置最大文件大小

我正在使用下面的代碼上傳文件,使用Apache文件上傳使用情況。

 ServletFileUpload upload = new ServletFileUpload(); 
     upload.setSizeMax(500000000); 
     upload.setProgressListener(aupl); 
     FileItemIterator iter = upload.getItemIterator(req);   

     while (iter.hasNext()) { 
      FileItemStream item = iter.next(); 
      if (!item.isFormField()) {     
       form_name = item.getFieldName();   
     InputStream stream = item.openStream();  
     FileOutputStream fop = new FileOutputStream(new File(temp_location)); 
     Streams.copy(stream, fop, true);     
      }    
     }     

我能找到的字段名稱的唯一方式是使用item.getFieldName(),我能做的,只有做upload.getItemIterator,但setSizeMax後(500 ..)必須在上傳設置在upload.getItemIterator被調用之前。

是否有解決此問題的方法?如果沒有解決方案,您是否可以建議任何其他文件上傳API來處理此問題。

感謝

+0

也許你可以爲每個文件類型使用不同的servlet。 500000000也是500MB - 那種大? – 2011-06-10 00:50:48

+0

爲測試目的將maxFileSize設置爲大於0,因爲我努力測試它,假設並將其設置爲0,當我把它放在1時它工作 – shareef 2016-07-22 12:08:51

回答

0

假設非表單變量的數量是有限的(你可以強制執行),只需使用迭代器,並使用一個包裝流周圍拋出一個異常時的總字節數(大量的基本計數器的實現存在 - 例如commons-io)超過N,其中N作爲構造函數中的限制提供。

eg 

    long limit = 500000; // bytes 
    long cumulativeSize=0; 

while { 
    if (limit - cumulativeSize <=0) break; 
... 
... 
... // FileItem 
    InputStream stream = item.openStream(); 
    stream = new LimiterStream(stream,100000); 
    Streams.copy(stream,fop,true); 
    FileOutputStream fop = new FileOutputStream(new File(temp_location)); 
    cumulativeSize += stream.getCount(); // you'd implement this too, to keep a running count 
    catch (SizeExceededException e ) { 
      System.out.println("you exceeded the limit I set of "+e.getLimit(); // implemented 
      break; 
    } 
    ... 
} // end while 
+0

您也可以計算表單域的長度並將它們添加到cumulativeSize .... – MJB 2011-06-10 05:31:25

1

如果你不是遍歷的FileItem對象,而不是FileItemStream對象,所有你需要做的是設置一些常數最大尺寸值,以及每個項目比較合適的值。如果一個項目超出了大小,請適當處理它(拋出新的異常,垃圾文件,無論你想做什麼),否則繼續正常運行。

final long MAX_RESUME_SIZE = 5242880; // 5MB -> 5 * 1024 * 1024 
final long MAX_TRANS_SIZE = 3145728; // 3MB -> 3 * 1024 * 1024 

DiskFileItemFactory factory = new DiskFileItemFactory(); 
String fileDir = "your write-to location"; 
File dest = new File(fileDir); 
if(!dest.isDirectory()){ dest.mkdir(); } 
factory.setRepository(dest); 
ServletFileUpload upload = new ServletFileUpload(factory); 

for (FileItem item: upload.parseRequest(request)) { // request -> the HttpServletRequest 
    if(!item.isFormField(){ 
     if(evaluateSize(item)){ 
      // handle as normal 
     }else{ 
      // handle as too large 
     } 
    } 
} // end while 

private boolean evaluateSize(FileItem item){ 
    if(/* type is Resume */ && item.getSize() <= MAX_RESUME_SIZE){ 
     return true; 
    }else if(/* type is Transcript */ && item.getSize() <= MAX_TRANS_SIZE){ 
     return true; 
    } 

    // assume too large 
    return false; 
} 

當然,你將不得不增加更多的邏輯,如果有比這兩種類型的文件較多,但你可以看到它是非常簡單不得不寫之前,你的文件大小進行比較。

相關問題