react-native FormData上传未发送正确的数据 [英] react-native FormData upload does not send the right data

查看:511
本文介绍了react-native FormData上传未发送正确的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找我能找到的所有问题,但似乎没有人遇到我的问题.

I've been looking through all the questions I could find but it looks like nobody had my problem.

我正在运行react-native 39,我想上传一张图片.看起来可以使用FormData上载它.

I'm running react-native 39 and I want to upload an image. It looks like that it is possible to upload it using FormData.

/**
 * Polyfill for XMLHttpRequest2 FormData API, allowing multipart POST requests
 * with mixed data (string, native files) to be submitted via XMLHttpRequest.
 *
 * Example:
 *
 *   var photo = {
 *     uri: uriFromCameraRoll,
 *     type: 'image/jpeg',
 *     name: 'photo.jpg',
 *   };
 *
 *   var body = new FormData();
 *   body.append('authToken', 'secret');
 *   body.append('photo', photo);
 *   body.append('title', 'A beautiful photo!');
 *
 *   xhr.open('POST', serverURL);
 *   xhr.send(body);
 */

使用该方法,我只在请求的正文中获得了[object Object]. 使用fetch而不是xhr可以获取一些数据,但是现在我可以预期,没有可以从服务器获取的图像

Using the method I just get [object Object] in the body of the request. Using fetch instead of xhr I get some data but now that I would expect, there's no image that I can get from the server

推荐答案

问题是表单不了解您要编码的对象中存储的信息意味着什么,因此它不会获取图片数据而是从设备中找出photo对象可能具有的正确"表示形式,通常是一个字符串.在这种情况下,[object Object].当然,您的服务器不会接受.实际上,这发生在所有非原始JavaScript类型上.您应该先使用JSON.stringify(photo)将其转换为JSON字符串.

The problem is that the Form has no idea about what the information stored in the object that you are trying to encode means, so it will not fetch the picture data from the device, and instead, just figure out the 'proper' representation that the photo object might have, and that is usually a string. In this case [object Object]. Of course, that won't be accepted by your server. In fact this happens to all non-primitive types of JavaScript. You should use JSON.stringify(photo) to convert it to a JSON string first.

相反,您可以尝试以FormData可以理解的格式从相机胶卷中检索图像数据,例如,用

Instead, what you can try is to retrieve the image data from the camera roll in a format that FormData can understand, for instance, a string that encodes your image in base64. This is not a functionality that comes with React Native, but a quick search retrieved some promising packages. Maybe have a look at:

  • react-native-image-to-base64
  • react-native-upload-from-camera-roll
  • this post
  • JS.coach
  • react-native-fs

然后,将图像以base64格式保存后,您可以执行以下操作:

Then, once you have your image in base64 format, you can do the following:

var photo = {
  data: myBase64Data,
  type: 'image/jpeg',
  name: 'photo.jpg',
};

var body = new FormData();
body.append('authToken', 'secret');
body.append('photo', JSON.stringify(photo));
body.append('title', 'A beautiful photo!');

xhr.open('POST', serverURL);
xhr.send(body);

希望有帮助.

这篇关于react-native FormData上传未发送正确的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆