Norman Bentley
Norman Bentley

Reputation: 660

Send Image from .NET Web API 2 Service to Android Retrofit

I have an image on a server stored in a file (not db). I want to display this image in a layout view in Android Studio. I am using Web API2 and retrofit to exchange data.

Using retrofit, I know I need to send the file encapsulated in a class. I am not aware of what type to create? (Byte array?) and how retrofit on the android side would convert this type. I have tried to use byte[] on boths side however retrofit was not able to read the byte[] from Json.

Would anyone be able to guide me on how I would go about transferring this jpeg image? Thanks!

Upvotes: 1

Views: 1584

Answers (1)

Roberto Orozco
Roberto Orozco

Reputation: 599

I've recently implemented it.

This is the method in my api.

[HttpPost]
public IHttpActionResult Upload()
{
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 0)
    {
        foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            // Do something with file.
        }
        else
        {
            // No files.
        }
    }

The class you are looking for is retrofit's TypedFile class. This is my implementation.

RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("baseurl").build();
ApiTaqueria api = restAdapter.create(ApiTaqueria.class);
TypedFile foto = new TypedFile("multipart/form-data", new File("path"));
api.subirLogoTaqueria(foto, new Callback<Taqueria>() {
    @Override
    public void success(Taqueria result, Response response) {
    // Do something.
    }

    @Override
    public void failure(RetrofitError retrofitError) {
    // Do something.
    }
});

In the retrofit interface.

@Multipart
@POST("/api/Photo/Upload")
public void subirLogoTaqueria(@Part("foto") TypedFile foto, Callback<Taqueria> callback);

Happy coding.

Upvotes: 2

Related Questions