Reputation: 157
I have a functional web service in Jersey, that consumes a multi part form data like videos and images and stores them on a directory. I am able to upload videos and images from a browser. Now I want to upload them from an Android application by selecting from gallery Intent or camera. How am I supposed to do so? Any help will be appreciated. Here is my web service code.
@Path("/fileupload")
public class UploadFileService {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
try {
String uploadedFileLocation = "/home/aamir/Downloads/" + fileDetail.getFileName();
// save it
saveToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation;
return output;
}
catch(Exception e)
{
return "error";
}
}
// save uploaded file to new location
private void saveToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 881
Reputation: 6392
You can use the Jersey client API in your Android app (or any other client API for that matter, Apache CXF springs to mind...). It lives in a standalone jar which you can add to your app as a dependency, then in your app create a shared client which you use to create requests.
From the Jersey client docs...
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");
Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");
MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
MyJAXBBean.class);
https://jersey.java.net/documentation/latest/client.html
Upvotes: 0
Reputation: 532
I suggest you use Retrofit to download the image. It's a great library for handling RESTful applications:
Use retrofit to download image file
Upvotes: 1