我已使用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