2012-02-25 66 views
1

我想上傳一個文件到我在Tomcat7上運行的Spring服務器。這是一個簡單的POST請求中,代碼如下:文件只部分上傳到服務器

@RequestMapping(method = RequestMethod.POST) 
    public void saveFile(HttpServletRequest request, @RequestParam("file_name") String fileName) { 
     Logger.getLogger(FileRestAction.class).info("saving file with name " + fileName); 
     try { 
      byte[] buf = readFromRequest(request); 
      String filePath = writeToFile(buf, fileName); 
      File_ file = new File_(filePath, request.getContentType()); 
      Logger.getLogger(FileRestAction.class).info(request.getContentType() + " " + request.getContentLength()); 
      fService.save(file); 
     } catch (IOException e) { 
      Logger.getLogger(FileRestAction.class).error("Failed to upload file. " + 
        "Exception is: " + e.getMessage()); 
     } 
    } 

    private String writeToFile(byte[] buf, String fileName) throws IOException { 
     String fileBasePath = ConfigurationProvider.getConfig().getString(Const.FILE_SAVE_PATH); 
     File file = new File(fileBasePath + fileName); 
     FileOutputStream fos = new FileOutputStream(file); 
     fos.write(buf); 
     fos.close(); 
     Logger.getLogger(FileRestAction.class).info("filepath: " + file.getAbsolutePath()); 
     return file.getAbsolutePath(); 
    } 

    private byte[] readFromRequest(HttpServletRequest request) throws IOException { 
     InputStream is = request.getInputStream(); 
     byte[] buf = new byte[request.getContentLength()]; 
     is.read(buf); 
     is.close(); 
     return buf; 
    } 

現在的問題是,在服務器上的文件僅僅是「半完成」,就好像所有字節不存在。例如,如果我發送大小爲54kB的256x256 .png文件,則寫在服務器上的文件也是54kB和256x256大小,但實際圖片在開頭附近切斷(其餘爲空)。沒有例外被拋出。

位的測試之後,我發現,截止大約15-20Kb(以下圖片是完全上傳)。

關於什麼可能會導致此問題的任何想法?

編輯:我改變了readFromRequest方法根據什麼GreyBeardedGeek建議。現在如下:

private byte[] readFromRequest(HttpServletRequest request) throws IOException { 
     InputStream is = request.getInputStream(); 
     int fileLength = (int) request.getContentLength(); 
     byte[] buf = new byte[fileLength]; 
     int bytesRead = 0; 
     while (true) { 
      bytesRead += is.read(buf, bytesRead, fileLength - bytesRead); 
      Logger.getLogger(FileRestAction.class).info("reading file: " + bytesRead + " bytes read"); 
      if (bytesRead == fileLength) break; 
     } 
     is.close(); 
     return buf; 
    } 

回答

2

InputStream.read不能保證讀取您要求的數據量。 您要求的大小是它將讀取的最大字節數。

這就是爲什麼read()方法返回實際讀取的字節數。 請參閱http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read(byte [])

所以,答案是多次讀取,直到讀取()返回-1