Ilkar
Ilkar

Reputation: 2177

RestTemplate upload image file

I need to create RestTemplate request, which will send image to upload by PHP application.

My code is:

Resource resource = new FileSystemResource("/Users/user/Documents/MG_0599.jpg");
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
    parts.add("Content-Type", "image/jpeg");
    parts.add("file", resource);
    parts.add("id_product", productId);

ResponseEntity<String> response = cookieRestTemplate.getForEntity(url, String.class, parts);

After start this app, PHP server send me information, that file is empty.

I was thinking, that problem is by PHP site, but i've installed POSTER plugin for Firefox, and i made GET request onto this same URL, but the file to upload, i've selected normaly like in web form (popup system window to select file). After this PHP program uploaded file without any problem.

I think, that problem is maybe with this, that i'm sending resource as value of param name:

parts.add("file", resource);

And on the POSTER plugin, i just select file from my file system ?

Can you help me ?

Upvotes: 4

Views: 12046

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

You aren't using the RestTemplate correctly. You are using the following method

public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> urlVariables)

So you see your MultiValueMap is going to be used as a source for URL variables which you don't actually seem to have. There are no request parameters sent in the request.

You won't actually be able to upload a file with any of the getForX methods.

You will have to use one of the exchange methods. For example

Resource resource = new FileSystemResource(
            "/Users/user/Documents/MG_0599.jpg");
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("Content-Type", "image/jpeg");
parts.add("file", resource);
parts.add("id_product", productId);

restTemplate.exchange(url, HttpMethod.GET,
            new HttpEntity<MultiValueMap<String, Object>>(parts),
            String.class); // make sure to use the generic type argument

Note, that it is very uncommon to do a file upload with a GET request.

Upvotes: 9

Related Questions