使用JAVA jax-rs将REST Web服务发送到多个映像的最佳方法是什么?
答案 0 :(得分:0)
虽然使用base64字符串是一种选择,但是有更好的方法可以在JAX-RS Web服务中发送文件。我个人建议创建一个方法来监听用户POST一个HTTP表单。此表单实际上可能包含您需要发送的所有信息以及标识符。
这类似于我将用于此类Web服务的方法定义。它与Jersey兼容,它允许用户通过基本HTML表单或任何POST请求发送文件。我强烈建议您查看构建Java Web服务的this article。它不包括“文件上传”方面,但它非常有用,它帮助我更多地了解Java Web服务的功能。
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/html")
public Response uploadFile(
@FormDataParam("username") String username,
@FormDataParam("password") String password,
@FormDataParam("title") String title,
@FormDataParam("file") InputStream fileInputString,
@FormDataParam("file") FormDataContentDisposition fileInputDetails) {
String status = null;
String fileLocation = "/home/user/uploadtest/test.png;
NumberFormat myFormat = NumberFormat.getInstance();
myFormat.setGroupingUsed(true);
// Save the file
try {
OutputStream out = new FileOutputStream(new File(fileLocation));
byte[] buffer = new byte[1024];
int bytes = 0;
long file_size = 0;
while ((bytes = fileInputString.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
file_size += bytes;
}
out.flush();
out.close();
status = "File has been uploaded to:" + fileLocation;
} catch (IOException ex) {
System.err.println("Unable to save file: " + fileLocation);
ex.printStackTrace();
}
return Response.status(200).entity(status).build();
}