タイトルはよく見えるかもしれませんが、それらのどれもが私の問題に適合しません。Resttemplate経由でスプリングレストサービス経由でファイルを送信
私は通常のパラメータとマルチパートの形式でファイルを受け入れる休憩サービスを持っています。
reststemplateを使用して、上記の休憩サービスにデータとファイルを送信します。
通常の文字列データを送信するまでは何の問題もありませんでした。一度私はバイトを送信するコードを追加します。400 Bad request error。
ByteArrayResourceを送信するコメントコードがあれば、通常のパラメータで動作します。以下
サンプルコード
レストサービスコントローラ
@RestController
@RequestMapping(value="/ticket")
public class UserTicketController {
@RequestMapping(value="/createTicket.do",method={RequestMethod.POST},
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},headers={"content-type="+MediaType.MULTIPART_FORM_DATA_VALUE})
public void createTicket(@ModelAttribute ServiceDeskRequest serviceDeskRequest, HttpServletRequest request,HttpServletResponse response) throws Exception{
}
}
がServicedeskrequestモデル属性が
public class ServiceDeskRequest implements Serializable{
private String jsonData;
private MultipartFile attachment;
}
アプリケーションのcontext.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
クライアントSでありますイドコード
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> requestParamerterMap = new LinkedMultiValueMap<String, Object>();
requestParamerterMap.add("jsonData", jsonData);
MultipartFile attachment = userRequest.getAttachment();
if(attachment!=null && attachment.getOriginalFilename()!=null) {
ByteArrayResource byteArrayResource = new ByteArrayResource(attachment.getBytes(), attachment.getOriginalFilename());
requestParamerterMap.add("attachment", byteArrayResource);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(requestParamerterMap, headers);
String response = restTemplate.postForObject(targetUrl, requestEntity, String.class);