java 创建 Rest Web 服务以接收图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5722406/
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
Create Rest Web Service to receive an Image
提问by c12
How would you design a REST based web service that receives an image file in the form of an InputStream
? If the InputStream
is posted to a REST end point, how does that end point receive it so that it can create an image file?
您将如何设计一个基于 REST 的 Web 服务,该服务以InputStream
. 如果InputStream
发布到 REST 端点,该端点如何接收它以便它可以创建图像文件?
采纳答案by Mallikarjuna
Example REST Web Service Java Class to Recieve Image
接收图像的 REST Web 服务 Java 类示例
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
@Path("/upload")
public class Upload_Documents {
private static final String UPLOAD_FOLDER = "c:/uploadedFiles/";
@Context
private UriInfo context;
/**
* Returns text response to caller containing uploaded file location
*
* @return error response in case of missing parameters an internal
* exception or success response if file has been stored
* successfully
*/
@POST
@Path("/pic")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
System.out.println("Called Upload Image");
// check if all form parameters are provided
if (uploadedInputStream == null || fileDetail == null)
return Response.status(400).entity("Invalid form data").build();
// create our destination folder, if it not exists
try {
createFolderIfNotExists(UPLOAD_FOLDER);
} catch (SecurityException se) {
return Response.status(500)
.entity("Can not create destination folder on server")
.build();
}
String uploadedFileLocation = UPLOAD_FOLDER + fileDetail.getFileName();
try {
saveToFile(uploadedInputStream, uploadedFileLocation);
} catch (IOException e) {
return Response.status(500).entity("Can not save file").build();
}
return Response.status(200)
.entity("File saved to " + uploadedFileLocation).build();
}
/**
* Utility method to save InputStream data to target location/file
*
* @param inStream
* - InputStream to be saved
* @param target
* - full path to destination file
*/
private void saveToFile(InputStream inStream, String target)
throws IOException {
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(target));
while ((read = inStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
/**
* Creates a folder to desired location if it not already exists
*
* @param dirName
* - full path to the folder
* @throws SecurityException
* - in case you don't have permission to create the folder
*/
private void createFolderIfNotExists(String dirName)
throws SecurityException {
File theDir = new File(dirName);
if (!theDir.exists()) {
theDir.mkdir();
}
}
}
回答by Tarlog
Receiving an InputStream is possible in JAX-RS. You just put the InputStream parameter without annotations:
在 JAX-RS 中可以接收 InputStream。您只需放置没有注释的 InputStream 参数:
@POST
public void uploadImage(InputStream stream) {
// store image
}
Pay attention that it will work for any content type.
请注意,它适用于任何内容类型。
Although it will work, I would suggest a more "JAX-RS way":
虽然它会起作用,但我建议更“JAX-RS 方式”:
1 Create provider that will create an image class (e.g. java.awt.Image) from the InputStream:
1 创建将从 InputStream 创建图像类(例如 java.awt.Image)的提供程序:
@Provider
@Consumes("image/jpeg")
class ImageProvider implements MessageBodyReader<Image> {
public Image readFrom(Class<Image> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException,
WebApplicationException {
// create Image from stream
}
}
2 Register the provider the same way you register a resource.
3 Make your resource class to receive Image instead of InputStream.
2 以注册资源的相同方式注册提供者。
3 使您的资源类接收 Image 而不是 InputStream。
Why is this approach better?
You separate the deserialization logic from your resource class. So if in the future you would like to support more image formats, you just need to add additional providers, while the resource will stay the same.
为什么这种方法更好?
您将反序列化逻辑与资源类分开。因此,如果将来您希望支持更多图像格式,您只需要添加额外的提供程序,而资源将保持不变。