3

I am doing an Application with Spring Rest Template for making the Box.net Rest Calls. But I am facing the Problem of Not Uploading the Files through Rest-template. It is giving an Error as "Bad Request 400 Http Status Code".

Here is my sample Code:

public static Object uploadfile(){ 

    String url="https://upload.box.com/api/2.0/files/content"; 
    String file_url="SOME URL or Local File System Path"; 

    File tmpFile = new File(file_url); 
    boxMap.add("filename",tmpFile); 
    boxMap.add("parent_id",747312798); 

    ResponseEntity<Object> response = restTemplate.exchange(url, 
    HttpMethod.POST, 
    new HttpEntity(boxMap,getHeaders()), 
    Object.class); 
    System.out.println("uploaded file info: "+response.getBody()); 
    return response.getBody(); 
}

Can anyone tell me the procedure how to upload files from Java Rest Template.

Marvo
  • 17,845
  • 8
  • 50
  • 74
Rajkumar
  • 31
  • 1
  • 2

2 Answers2

0

File uploads need to be performed as multipart POSTs. Instructions on how to do this in Java can be found here: How can I make a multipart/form-data POST request using Java?

Community
  • 1
  • 1
seanrose
  • 8,185
  • 3
  • 20
  • 21
  • Hi Seanrose, I gone through your link and I successfully uploaded the files to Box.net. But, I have a scenario to upload the files by using file web URL(Ex: http://example.com/sample.txt). Is Box supports these type of File uploading? Or it supports only Local Files. – Rajkumar Apr 03 '13 at 13:28
0

I've solved this issue with restTemplate.
Please, see some code examples:

public String uploadPhoto(File file, String token) throws ClientRequestException {
    try {
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        UrlResource urlr = new UrlResource("file:" + file.getAbsolutePath());
        form.add("attachment", urlr);
        WsUrl wsUrl =  requestForObjectMultipart("/uploadProfilePhoto.json", form, WsUrl.class, token);
        return wsUrl.getUrl();
    } catch (MalformedURLException e) {
        throw new ClientRequestException("Something went wrong with file upload");
    }
}


protected <T extends ErrorAware> T requestForObjectMultipart(String methodUrl, Object r, Class<T> c, String token) throws ClientRequestException{
        HttpHeaders headers = new HttpHeaders();
        headers.add(SECURITY_TOKEN,token);
        //Need to set content type here to avoid convertion with Jackson message converter
        headers.add("Content-Type", "multipart/form-data");
        return requestForObjectWithHeaders(methodUrl, r, c, HttpMethod.POST, headers);
    }

protected <T extends ErrorAware> T requestForObjectWithHeaders(String methodUrl, Object r, Class<T> c, HttpMethod method, HttpHeaders headers) throws ClientRequestException{
        T result = restTemplate.exchange( getBaseUrl() + getApiUrlPref() + methodUrl, method, new HttpEntity<Object>(r,headers), c).getBody();
        if( result.hasError() )
            throw new ClientRequestException(result.getError());
        return result;
    }

String token - it is only security token(provided ascustom HTTP header) on our rest services. It can serve an example how to setup "Custom headers" in request. Note: pay attention that returned data(from web-service after upload file) is parsed as JSON object. If you do not want this - you can simply ignore result of restTemplate.exchange() method.

My restTemplate initialization in Spring config:

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <property name="messageConverters">
            <list>
                <ref bean="jsonConverter"/>
                <bean class="org.springframework.http.converter.FormHttpMessageConverter" />
            </list>
        </property>
        ...
    </bean>
<!-- To enable @RequestMapping process on type level and method level -->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonConverter"/>
            </list>

        </property>
    </bean>

    <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes" value="application/json"/>
    </bean>
Oleksandr_DJ
  • 1,454
  • 2
  • 14
  • 26