java 通过 REST 发送/接收图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42432609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send/Receive images via REST
提问by A.D
I am using grizzly for java rest service and consuming these web services in an android app.
我将 grizzly 用于 java rest 服务并在 android 应用程序中使用这些 web 服务。
Its working fine as far as "text" data is concerned.
就“文本”数据而言,它的工作正常。
Now I want to load the images(from server) in my android application, using this rest service and also allow the users to update image from the device.
现在我想在我的 android 应用程序中加载图像(来自服务器),使用这个休息服务,并允许用户从设备更新图像。
I have tried this code
我试过这个代码
@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();
}
The code above allow me to download the file, but is it possible to display result in broswer? like this http://docs.oracle.com/javase/tutorial/images/oracle-java-logo.png
上面的代码允许我下载文件,但是可以在浏览器中显示结果吗?像这样 http://docs.oracle.com/javase/tutorial/images/oracle-java-logo.png
采纳答案by A.D
Solution of Part 1:
第 1 部分的解决方案:
I have made the changes in my code as suggested by Shadow
我已按照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();
}
Requested image will be displayed in browser
请求的图像将显示在浏览器中
Part 2:The code used to convert back Base64 encoded image
第 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;
}