在 react-native 中上传 blob/文件,内容为空 [英] Uploading blob/file in react-native, contents is empty

查看:46
本文介绍了在 react-native 中上传 blob/文件,内容为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够从我的网络浏览器成功上传一个包含正确内容的 blob,但是当我从 react-native 上传时,上传文件是空的.代码如下:

I am able to succesfully upload a blob with proper contents from my web browser, but when I do it from react-native, the upload file is empty. Here is the code:

    async function doit() {
        const data = new FormData();
        data.append('str', 'strvalue');
        data.append(
          'f',
          new File(['foo'], 'foo.txt', {type: 'text/plain'}),
        );

        await fetch('http://localhost:3002/upload', {
            method: 'POST',
            body: data
          });
    }

但是从 react-native 执行相同的代码,它会上传,但文件是空的.

However doing this same code from react-native, it uploads, but the file is empty.

这是我用来测试的 node.js 服务器.加载 http://localhost:3002 会为您提供一个名为upload it"的按钮.单击它会从网络上传.结果截图如下.

Here is the node.js server I am using to test this. Loading http://localhost:3002 gives you a button called "upload it". Clicking it does the upload from the web. Screenshots of results are below.

var multiparty = require('multiparty');
var http = require('http');

http
  .createServer(function (req, res) {
    if (req.url === '/upload' && req.method === 'POST') {
      console.log('multipart here');
      var form = new multiparty.Form();

      form.parse(req, function (err, fields, files) {
        console.log(require('util').inspect({ fields, files }, false, null, true));
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({ bar: true }));
      });

      return;
    }

    console.log('here');
    // show a file upload form
    res.writeHead(200, { 'content-type': 'text/html' });
    res.end(
        `
        <script>
        async function doit() {
            const data = new FormData();
            data.append('str', 'strvalue');
            data.append(
              'f',
              // new File([new Blob(['asdf'], {type : 'text/plain'})], 'filename.txt'),
              new File(['foo', 'what', 'the', 'hell'], 'foo.txt', {type: 'text/plain'}),
            );

            const res = await fetch('http://localhost:3002/upload', {
                method: 'POST',
                body: data
              });
              console.log(JSON.stringify(res, null, 4));
        }
        document.addEventListener('DOMContentLoaded', () => {
            document.getElementById('b').addEventListener('click', doit, false)
        }, false);
        </script>
        <button type="button" id="b">upload it</button>
        `
    );
  })
  .listen(3002);

从网络浏览器我们看到节点服务器记录了这个,注意文件大小是 14.

推荐答案

我最近在将 图像 从 react-native 应用程序发布到服务器时遇到了同样的问题.但是,我能够通过将文件的名称和类型附加到 formData 实例来使其工作.

I faced the same problem recently while posting an image from a react-native app to a server. However, I was able to make it work by appending the name and type of the file to the formData instance.

此处,uploadImageAsyncuri 参数作为路由参数从上一屏幕传递.

Here, the uri argument to uploadImageAsync is passed as a route parameter from the previous screen.

const postShoutHandler = async () => {
  setShoutUploadStatus("Started Upload");
  const response = await uploadImageAsync(route.params.captures);
  const uploadResult = await response.json();
  if (uploadResult === "Upload successful") {
    setShoutUploadStatus("Success");
    navigation.navigate("Home");
  } else {
    setShoutUploadStatus("Failed");
  }
};
/* <--Upload image function --> */
const uploadImageAsync = (uri: string) => {
  const apiUrl = "https://www.yourserver.com/image";
  let uriParts = uri.split(".");
  let fileType = uriParts[uriParts.length - 1];
  let formData = new FormData();
  formData.append("img", {
    uri,
    name: `photo.${fileType}`,
    type: `image/${fileType}`,
  });

  formData.append("description", "HEY");
  let options = {
    method: "POST",
    body: formData,
    headers: {
      Accept: "application/json",
      "Content-Type": "multipart/form-data",
      Authorization: "Bearer " + accessToken,
    },
  };
  return fetch(apiUrl, options);
};
/* <--Upload image function --> */

这是图像配置.

 const photoData = await camera.takePictureAsync({
      base64: true,
      exif: false,
    });

这篇关于在 react-native 中上传 blob/文件,内容为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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