我一直在我的android应用程序中成功地使用spring for android来从/向服务器获取/发布数据。现在,我必须对多部分表单进行发布请求,但我无法让它按照我想要的方式工作。
用例: 1. 从图库中挑选一张照片 2. 使用文件源将其加载到位图 3. 将位图压缩为 ByteArrayOutputStream 4. 将字节数组 ( ByteArrayOutputStream.toByteArray() ) 传递给服务器。(我需要将此作为 jpeg 而不是 application/octet-stream 发送)
上传照片的服务器端点接受仅具有以下 Mime 类型的 MultipartFile(注意,它不接受 MimeType: application/octet-stream):
GIF("image/gif")
PNG("image/png", "image/x-png")
JPG("image/jpeg", "image/jpg", "image/pjpeg")
BMP("image/bmp")
我试过使用示例代码,但到目前为止还没有成功。
使用以下代码,我收到以下错误: org.springframework.web.bind.MissingServletRequest ParameterException: Required MultipartFile parameter 'file' is not present
非常感谢您对此事的帮助。谢谢并继续努力。
这是我的代码:
bitmap = BitmapFactory.decodeFile("/mnt/sdcard/DCIM/Camera/20130205_162546.jpg");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 60, bos);
byte[] data = bos.toByteArray();
// populate the data to post
MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>();
formData.add("caption", "Test Caption");
formData.add("file", data);
// The URL for making the POST request
final String url = "http://api.example.com/imageUpload?oauth_token=XXXXXX";
HttpHeaders requestHeaders = new HttpHeaders();
// Sending multipart/form-data
requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
// Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate(true);
// // Set a custom message converter that supports the application/json media type
// final GsonHttpMessageConverter gsonMessageConverter = new GsonHttpMessageConverter();
// gsonMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
// final ByteArrayHttpMessageConverter byteArrayMessageConverter = new ByteArrayHttpMessageConverter();
// byteArrayMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.IMAGE_JPEG));
// final FormHttpMessageConverter formMessageConverter = new FormHttpMessageConverter();
// formMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.IMAGE_JPEG));
// restTemplate.getMessageConverters().addAll(Arrays.asList(gsonMessageConverter, byteArrayMessageConverter, formMessageConverter));
// Make the network request, posting the message, expecting a String in response from the server
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
// Return the response body to display to the user
Log.i(TAG, "**** response.body : " + response.getBody());