I'm trying to send a file from android to my webserver through a Rest API, but I don't know how to handle the MultipartBody.Part object in java.
API Request:
@Multipart
@POST("utilizadores/upload")
Call<ResponseBody> uploadPhoto(
@Part MultipartBody.Part fotografia);
Android Code:
File file = new File(getPath(data));
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part parts = MultipartBody.Part.createFormData("images", file.getName(), requestBody);
Call<ResponseBody> call = RetrofitClient
.getInstance()
.getApi()
.uploadPhoto(parts);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(getContext(), response.message(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
Java Code:
- What should I pass as parameter in the next function 'uploadFile()'?
- The value of fotografia is '(NULL)'.
@POST
@Path("/upload")
@Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(@QueryParam("fotografia") String fotografia) {
BD bd = new BD();
int id = 54;
try {
String path = "/fotografias/" + id + ".jpg";
//guardarFicheiro(fotografia, path);
ConnectionBD connection = bd.abrirLigacao();
PreparedStatement ps = connection.getConn()
.prepareStatement("UPDATE utilizador SET fotografia=? WHERE id=?");
ps.setString(1, fotografia);
ps.setInt(2, id);
int x = ps.executeUpdate();
if (x > 0) {
bd.fecharConexao(connection);
return Response.ok().build();
}
bd.fecharConexao(connection);
} catch (SQLException ex) {
System.out.println(ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}