通过REST发送/接收图像

通过REST发送/接收图像

问题描述:

我正在使用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

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; 
}