0

I have below request that works correctly in curl and all things are OK. I need to do that by use of spring and RestTemplate.

curl 'http://myweb.web.com/upload/temp/myImage.jpg' -X PUT  -H 'Origin:  http://myweb.web.com' -H 'Connection: keep-alive' -H 'Referer: http://myweb.web.com/new'  --data-binary @/opt/myImage.jpg 
2
  • this is controller in server side but i need client side code. so i said help me by RestTemplate code Commented Jan 23, 2020 at 16:41
  • Ah, my mistake. Deleted. Commented Jan 23, 2020 at 16:45

1 Answer 1

2

You can do something like this:

public void uploadFileTemplate() throws IOException {
        MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
        bodyMap.add("user-file", getUserFileResource());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/upload",
                HttpMethod.POST, requestEntity, String.class);
        System.out.println("response status: " + response.getStatusCode());
        System.out.println("response body: " + response.getBody());
    }

    public static Resource getUserFileResource() throws IOException {
        //todo replace tempFile with a real file
        Path tempFile = <path-to-your-imagefile>
        System.out.println("uploading: " + tempFile);
        File file = tempFile.toFile();
        return new FileSystemResource(file);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

thanks , i used it but it is not ok. this code not equivalence to my curl, because curl has ok response and use code get exception. exception wrapped by server and i can not report it
@abbaskarimi No one will give you end to end running code, you will need to add all other code parts which will be required. I just provided you the template so you can add your requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.