user3102349
user3102349

Reputation: 21

Retrofit file upload, objects are null on the server side

I want to send a photo from local android gallery to the server http Tomcat. For the communication I'm using retrofit. I've established the connection between device and server, and the programme get into servers function but all objects in params are null.

That's the device function declaration on the client side:

@Multipart
@POST("/monument/photo/upload")
void addMonumentPhoto(@Part("MonumentID") Integer monumentId,
                      @Part("name") String name,
                      @Part("subscript") String subscript,
                      @Part("photo") TypedFile photo,
                      Callback<Photo> callback);

... and that's how I call it:

photo = _resizePhoto(new File(monument.getUriZdjecie()));
typedFile = new TypedFile("multipart/mixed", photo);
//long bytes = photo.length();

  if (photo.exists()) {
      MonumentsUtil.getApi().addMonumentPhoto(monument.getIdZabytek(),
          "podpis",
          "Main photo",
           typedFile,
           new Callback<Photo>() {
           @Override
           public void success(Photo aPhoto, Response response) {

                  monument.setUriZdjecie(aPhoto.getUri());

                  MonumentsUtil.getApi().addMonument(monument.getNazwa(),
                                            monument.getOpis(),
                                            monument.getDataPowstania(),
                                            monument.getWojewodztwo(),
                                            monument.getUriZdjecie(),
                                            monument.getMiejscowosc(),
                                            monument.getKodPocztowy(),
                                            monument.getUlica(),
                                            monument.getNrDomu(),
                                            monument.getNrLokalu(),
                                            monument.getKategoria(),
                                            monument.getLatitude(),
                                            monument.getLongitude(),
                                            new MonumentsCallback());
           }
           @Override
           public void failure(RetrofitError retrofitError) {
                 Log.e(TAG, retrofitError.getMessage());
           }
     });
}

and the server's method:

@RequestMapping(value = "/monument/photo/upload")
public
@ResponseBody
Photo requestMonumentPhotoAdd(@RequestParam(value = "MonumentID", required = false) Integer monumentId,
                              @RequestParam(value = "name", required = false) String name,
                              @RequestParam(value = "subscript", required = false) String subscript,
                              @RequestParam(value = "photo", required = false) MultipartFile file,
                              HttpServletRequest request) {

    Photo photo = new Photo();
    if (monumentId != null)
        photo.setIdZabytek(monumentId);
    photo.setUri(URL + "/images/" + name);
    photo.setPodpis(subscript);
    photo = monumentsRepo.addPhoto(photo);
    String filePath = "D:\\Projects\\Images\\" + monumentId + "_" + photo.getIdZjecia();

    if (file != null) {
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(filePath)));
                stream.write(bytes);
                stream.close();
                photo.setUri(filePath);
                monumentsRepo.updatePhoto(photo);
                return photo;
            } catch (Exception e) {
                return null;
            }
        } else {
            return null;
        }
    }
    else {
        return null;
    }
}

Can anybody help me and explain why all objects after geting into the servers method are null? Maybe method is wrogly writen or the mime field of TypedFile is wrogly chosen but I read that the "multipart/mixed" mime type is for messages with various types of object included in message. I don't have any idea so any advice will be helpful.

Upvotes: 2

Views: 5211

Answers (2)

techhunter
techhunter

Reputation: 400

I also had the similar problems and after few hours trying I finally built image uploading functionality to remote server.

To upload image you need to create the API properly and also need to pass the image properly.

This should work fine for you:

In Retrofit client you need to set up the image as followed:

String photoName = "20150219_222813.jpg";
File photo = new File(photoName );
TypedFile typedImage = new TypedFile("application/octet-stream", photo);


RetrofitClient.uploadImage(typedImage, new retrofit.Callback<Photo>() {

            @Override
            public void success(Photo photo, Response response) {
                Log.d("SUCCESS ", "SUCCESS RETURN " + response);
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });

API SET UP:

@Multipart
@POST("/")
void uploadImage(@Part("file") TypedFile file, Callback<Photo> callback);

Remote Server Side PHP Code to handle the image:

........
$pic = 'uploaded_images/' . $imagename . '.jpg';
if (!move_uploaded_file($_FILES['file']['tmp_name'], $pic)) {
   echo "posted";
}
.........

If it helps any one please recognize me..thanks a lot..

Upvotes: 0

Colin M.
Colin M.

Reputation: 455

Try when creating your TypedFile object to use "image/*" as your mime type. For that "part" it is of that specific type. The "mixed" is likely for the submit as a whole, not the single part that is the file.

typedFile = new TypedFile("image/*", photo);

Upvotes: 1

Related Questions