我已使用restTemplate解决了此问题。
请,看到一些代码示例:
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;
}
字符串标记 - 它只是安全令牌(提供ascustom HTTP标头)在我们休息的服务。它可以举例说明如何在请求中设置“自定义标题”。 注意:注意返回的数据(从上传文件后的web服务)被解析为JSON对象。 如果你不想要这个 - 你可以简单地忽略restTemplate.exchange()方法的结果。在Spring配置
我restTemplate初始化:
<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>
嗨Seanrose,我通过你的链接过去了,我的文件,成功上传至Box.net。但是,我有一个使用文件Web URL(例如http://example.com/sample.txt)上传文件的场景。 是否Box支持这些类型的文件上传?或者它只支持本地文件。 – Rajkumar
目前只有档案。 – seanrose