java 使用 spring for android 使用压缩的 jpeg 字节数组制作多部分发布请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14738394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:12:50  来源:igfitidea点击:

Making a multipart post request with compressed jpeg byte array with spring for android

javaandroidspringpostmultipartform-data

提问by Nalin Mello

I've been using spring for android successfully in my android app to get/post data from/to the server. Now, I have to do a post request for a multipart form, but I've been unable to get it working the way I want.

我一直在我的 android 应用程序中成功地使用 spring for android 从/向服务器获取/发布数据。现在,我必须为multipart form做一个 post 请求,但我一直无法让它按照我想要的方式工作。

Use case: 1. Pick a photo from the gallery 2. Load it to a bitmap using the file source 3. Compress the bitmap to a ByteArrayOutputStream 4. Pass the byte array ( ByteArrayOutputStream.toByteArray() ) to the server. (I need to send this as jpeg not application/octet-stream)

用例: 1. 从图库中选择一张照片 2. 使用文件源将其加载到位图 3. 将位图压缩为 ByteArrayOutputStream 4. 将字节数组 ( ByteArrayOutputStream.toByteArray() ) 传递给服务器。(我需要将此作为 jpeg 发送,而不是应用程序/八位字节流)

The server endpoint for upload photo accepts a MultipartFile with only the following Mime types ( Note, it does not accept MimeType: 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")

I've tried using the sample code, but been unsuccessful so far.

我试过使用示例代码,但到目前为止没有成功。

With the following code I get the following error: org.springframework.web.bind.MissingServletRequest ParameterException: Required MultipartFile parameter 'file' is not present

使用以下代码,我收到以下错误:org.springframework.web.bind.MissingServletRequest ParameterException: Required MultipartFile parameter 'file' is not present

Help on this matter is greatly appreciated. Thanks and keep up the good work.

非常感谢对此事的帮助。谢谢,并保持良好的工作。

Here's my code:

这是我的代码:

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());

回答by gunar

I've bumped into the same kind of problem and the solution was to override the org.springframework.core.io.Resource#getFileName()implementation.

我遇到了同样的问题,解决方案是覆盖org.springframework.core.io.Resource#getFileName()实现。

In my case:

就我而言:

MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
// add values to map ... and when it comes to image:
Resource res = new ByteArrayResource(Utils.uriToByteArray(context, itemImage)) {
                    @Override
    public String getFilename() throws IllegalStateException {
        return imageFileName;
    }
};
HttpHeaders imageHeaders = new HttpHeaders();
imageHeaders.setContentType(MediaType.IMAGE_JPEG);
HttpEntity<Resource> imageEntity = new HttpEntity<Resource>(res, imageHeaders);
map.add("item[image]", imageEntity);

Where imageFilename is the file name. That will be later included as multipart header: Content-Disposition: form-data; name="your_image_form_item"; filename="20130520_142401.jpg"

其中 imageFilename 是文件名。稍后将作为多部分标题包含在内:Content-Disposition: form-data; name="your_image_form_item"; filename="20130520_142401.jpg"

I hope it helps!

我希望它有帮助!

回答by TrueCoke

I too suffered this issue. Turned out that the body of my issue was on the server, server was not configured to handle/resolve multipart request.

我也遇到了这个问题。原来我的问题的主体在服务器上,服务器没有配置为处理/解决多部分请求。

Check out my detailed answer here. Hope it helps.

在这里查看我的详细答案。希望能帮助到你。