2013-05-10 30 views
0

我想上傳文件,但我沒有通過html表單來完成。 QueryParam和PathParam不能使用。那麼誰能說出如何傳遞流。作爲參數傳遞InputStream到網絡服務

我HttpClient的樣子:

try 
    { 
     HttpClient httpclient = new DefaultHttpClient(); 
     InputStream stream=new FileInputStream(new File("C:/localstore/ankita/Desert.jpg")); 
     String url="http://localhost:8080/Cloud/webresources/fileupload"; 
     HttpPost httppost = new HttpPost(url); 
     HttpResponse response = httpclient.execute(httppost); 
    } 
    catch(Exception e){} 

和我的Web服務類頗像:

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

@POST 
@Consumes(MediaType.APPLICATION_OCTET_STREAM) 

public Response uploadFile(InputStream in) throws IOException 
{  
    String uploadedFileLocation = "c://filestore/Desert.jpg" ; 

    // save it 
    saveToFile(in, uploadedFileLocation); 

    String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation; 

    return Response.status(200).entity(output).build(); 

} 

// save uploaded file to new location 
private void saveToFile(InputStream uploadedInputStream,String uploadedFileLocation) 
{ 
    try { 
     OutputStream out = null; 
     int read = 0; 
     byte[] bytes = new byte[1024]; 

     out = new FileOutputStream(new File(uploadedFileLocation)); 
     while ((read = uploadedInputStream.read(bytes)) != -1) 
     { 
      out.write(bytes, 0, read); 
     } 
     out.flush(); 
     out.close(); 
    } catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 

} 

}

誰能幫助?

String url="http://localhost:8080/Cloud/webresources/fileupload"; 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url); 
     InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(new File("C:/localstore/ankita/Desert.jpg")), -1); 
     reqEntity.setContentType("binary/octet-stream"); 
     reqEntity.setChunked(true); // Send in multiple parts if needed 
     httppost.setEntity(reqEntity); 
     HttpResponse response = httpclient.execute(httppost); 

Web服務的外觀如何?

回答

1

你不能那樣做。您無法在HTTP請求中傳遞流,因爲流不可序列化。

要做到這一點的方法是創建一個HttpEntity來包裝流(例如InputStreamEntity),然後使用setEntity將其附加到HttpPOST對象。然後發送POST,客戶端將從您的流中讀取併發送字節作爲請求的「POST數據」。

+0

感謝您的回覆。我會盡力這樣做。會告訴你它是否有效。 – 2013-05-10 16:22:14

+0

我有下面的事情,但Web服務將如何調用?最後添加了上面的代碼。 – 2013-05-10 16:35:12

相關問題