Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 573
Ilkar Avatar asked Oct 19 '25 13:10

Ilkar


1 Answers

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.

like image 157
Sotirios Delimanolis Avatar answered Oct 21 '25 02:10

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!