2017-02-24 104 views
0

我正在使用grizzly for java rest服務並在android應用程序中使用這些Web服務。通過REST發送/接收圖像

就「文本」數據而言,它的工作很好。

現在我想在我的android應用程序中使用此rest服務加載圖像(從服務器),並允許用戶從設備更新圖像。

我已經試過這個代碼

@GET 
@Path("/img3") 
@Produces(MediaType.APPLICATION_OCTET_STREAM) 
public Response getFile() 
{ 
    File file = new File("img/3.jpg"); 
    return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM).header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"") // optional 
      .build(); 
} 

上面的代碼讓我下載的文件,但它可以顯示導致broswer?這樣 http://docs.oracle.com/javase/tutorial/images/oracle-java-logo.png

+0

'但是可以在broswer?中顯示結果嗎?那麼你會嘗試我的想法。所以請報告。 – greenapps

+0

@greenapps我很抱歉,我不明白我應該報告什麼。我仍然在尋找解決方案來在瀏覽器中顯示結果 –

+0

內容處置應該內聯,媒體類型應該是一個適當的jpeg MIME類型,而不是一個通用的八位字節流。 – Shadow

回答

0

1部分的解決方案:

我已經在我的代碼的變化由Shadow

@GET 
@Path("/img3") 
@Produces("image/jpg") 
public Response getFile(@PathParam("id") String id) throws SQLException 
{ 

    File file = new File("img/3.jpg"); 
    return Response.ok(file, "image/jpg").header("Inline", "filename=\"" + file.getName() + "\"") 
      .build(); 
} 

請求的圖像將顯示在瀏覽器

的建議第2部分: 用於轉換回Base64編碼圖像的代碼

@POST 
@Path("/upload/{primaryKey}") 
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) 
@Produces("image/jpg") 
public String uploadImage(@FormParam("image") String image, @PathParam("primaryKey") String primaryKey) throws SQLException, FileNotFoundException 
{ 
    String result = "false"; 
    FileOutputStream fos; 

    fos = new FileOutputStream("img/" + primaryKey + ".jpg"); 

    // decode Base64 String to image 
    try 
    { 

     byte byteArray[] = Base64.getMimeDecoder().decode(image); 
     fos.write(byteArray); 

     result = "true"; 
     fos.close(); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 

    return result; 
}