Reputation: 606
I have REST API in java that take image file and save on the server i want to return the path of that uploaded image in XML form but don't know how to do it.Currently it returns the response as a string in the browser.
Here is my code.
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();
}
}
}
Upvotes: 1
Views: 8961
Reputation: 1567
If you want to return xml from Rest, try to create Object with some fields. and Object and field will have @XmlRootElement @XmlElement and put @Produces("application/xml") on top of method signature.
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/xml")
public Response uploadFile(...){
//body
}
also you can use @produces(MediaType.APPLICATION_XML)
instead of @Produces("application/xml")
. both are same.
Upvotes: 3