0

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();
}
  • I think you have to check this solution https://stackoverflow.com/questions/39953457/how-to-upload-image-file-in-retrofit-2 – axar Apr 04 '21 at 06:55
  • This solution don't help me, because my problem is the parameter of the REST server function. – Alexandre Leite Lopes Apr 04 '21 at 10:17
  • I think you have to pass static image name so the system cannot understand your name they want acthule file so please check your code properly – axar Apr 04 '21 at 11:10

0 Answers0