【发布时间】:2016-01-27 13:51:15
【问题描述】:
我在 java 中有 REST API,它获取图像文件并保存在服务器上浏览器。
这是我的代码。
package com.javacodegeeks.enterprise.rest.jersey;
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.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
@Path("/files")
public class JerseyFileUpload {
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/home/hassan/Downloads/";
/**
* Upload a File
*/
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();
// save the file to the server
saveFile(fileInputStream, filePath);
String output = "File saved to server location : " + filePath;
return Response.status(200).entity(output).build();
}
// save uploaded file to a defined location on the server
private void saveFile(InputStream uploadedInputStream,
String serverLocation) {
try {
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
这并不能解决您声称的问题,但我希望图像文件的位置将在响应的
Location标头中返回。 -
output是一个字符串。您需要返回一个带有@XmlElement注释的类的实体(实例) -
我可以在同一个类中使用 Produces 注释,因为 Consumes 注释也在这里我可以同时使用两者吗。@RobAu 如何使用 @XmlElement,因为我很新。