2013-07-04 29 views
2

我使用的是Jersey,我可以上傳文件,也可以將虛擬blob寫入數據存儲區。但我堅持寫入我上傳到數據存儲的文件。如何從InputStream存儲Blob

@Path("/blob/") 
public class UploadFileService { 

    @POST 
    @Path("/upload/") 
    @Consumes(MediaType.MULTIPART_FORM_DATA) 
    public Response uploadFile(@FormDataParam("file") InputStream stream, @FormDataParam("file") FormDataContentDisposition disposition) throws IOException { 

     storeBlob(); 

     return Response.ok().build(); 
    } 

    public void storeBlob() throws IOException{ 


     // Get a file service 
      FileService fileService = FileServiceFactory.getFileService(); 

      // Create a new Blob file with mime-type "text/plain" 
      AppEngineFile file = fileService.createNewBlobFile("text/plain"); 

      // Open a channel to write to it 
      boolean lock = false; 
      FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock); 

      // Different standard Java ways of writing to the channel 
      // are possible. Here we use a PrintWriter: 
      PrintWriter out = new PrintWriter(Channels.newWriter(writeChannel, "UTF8")); 
      out.println("The woods are lovely dark and deep."); 
      out.println("But I have promises to keep."); 

      // Close without finalizing and save the file path for writing later 
      out.close(); 
      String path = file.getFullPath(); 

      // Write more to the file in a separate request: 
      file = new AppEngineFile(path); 

      // This time lock because we intend to finalize 
      lock = true; 
      writeChannel = fileService.openWriteChannel(file, lock); 

      // This time we write to the channel directly 
      writeChannel.write(ByteBuffer.wrap 
        ("And miles to go before I sleep.".getBytes())); 

      // Now finalize 
      writeChannel.closeFinally(); 

      // Later, read from the file using the Files API 
      lock = false; // Let other people read at the same time 
      FileReadChannel readChannel = fileService.openReadChannel(file, false); 

      // Again, different standard Java ways of reading from the channel. 
      BufferedReader reader = 
        new BufferedReader(Channels.newReader(readChannel, "UTF8")); 
       String line = reader.readLine(); 
      // line = "The woods are lovely dark and deep." 

      readChannel.close(); 

      // Now read from the file using the Blobstore API 
      BlobKey blobKey = fileService.getBlobKey(file); 
      BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService(); 
      String segment = new String(blobStoreService.fetchData(blobKey, 30, 40)); 
    } 
} 
+0

請您詳細說明在您編寫的代碼中不起作用的內容嗎? –

回答

0

如果我正確理解你的問題,你測試代碼工作:

// This time we write to the channel directly 
writeChannel.write(ByteBuffer.wrap, "And miles to go before I sleep.".getBytes()); 

但是當你試圖讀你的InputStream你只是上傳它不工作。


幾個軌道遵循:
1)你的函數使用@FormDataParam(「文件」)兩個參數有不同的類型(流和處置)。看起來不正確。

2)你確定上傳的文件是否爲空?

3)嘗試直接從磁盤讀取文件,無需上傳。它可以幫助您確定問題是否來自上傳。