代码之家  ›  专栏  ›  技术社区  ›  Gustavo Mendonça

将图像从React Native上载到LoopBack

  •  0
  • Gustavo Mendonça  · 技术社区  · 7 年前

    我需要将用户从CameraRoll选择的图像上载到环回组件存储。问题是组件存储工作正常,因为我可以通过Postman上传和下载文件。但是,当我尝试从react native上传到loopback时,它总是返回http状态为400的“No file content upload”。

    我读了很多人谈论它,尝试了一切,但没有一个对我有效。

    [
      {
        exists: 1,
        file: "assets-library://asset/asset.JPG?id=3FF3C864-3A1A-4E55-9455-B56896DDBF1F&ext=JPG",
        isDirectory: 0,
        md5: "428c2e462a606131428ed4b45c695030",
        modificationTime: 1535592967.3309255,
        size: 153652,
        uri: null
      }
    ]
    

    在上面的例子中,我只选择了一个图像。

    [
      {
        _data: {
          blobId: "3FF3C864-3A1A-4E55-9455-B56896DDBF1F",
          name: "asset.JPG",
          offset: 0,
          size: 153652,
          type: "image/jpeg"
        }
      }
    ]
    

    所以在这之后我尝试了很多事情,尝试将blob本身作为请求主体发送,尝试附加到表单数据并发送表单数据,但不管我尝试的方式如何,我总是得到“无文件内容上载”的响应。

    我也试过Facebook上的例子,但没有成功: https://github.com/facebook/react-native/blob/master/Libraries/Network/FormData.js#L28

    我现在的方式是:

      finalizarCadastro = async () => {
        let formData = new FormData();
        let blobs = [];
        for(let i=0;i<this.state.fotos.length;i++){
          let response = await fetch(this.state.fotos[i]);
          let blob = await response.blob();
          blobs.push(blob);
        }
        formData.append("files", blobs);
        this.props.servico.criar(formData);
      }
    

    以及发送到我的服务器的函数:

    criar: (servico) => {
      this.setState({carregando: true});
      axios.post(`${REQUEST_URL}/arquivos/seila/upload`, servico, {headers: {'content-type': 'multipart/form-data'}}).then(() => {
        this.setState({carregando: false});
        this.props.alertWithType("success", "Sucesso", "Arquivo salvo com sucesso");
      }).catch(error => {
        this.setState({carregando: false});
        console.log(error.response);
        this.props.alertWithType("error", "Erro", error.response.data.error.message);
      })
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Gustavo Mendonça    7 年前

    我找到了解决办法。所以问题实际上不是代码本身,而是同时发送多个文件。为了解决所有问题,我做了这样的事:

    this.state.fotos.forEach((foto, i) => {
      formData.append(`foto${i}`, {
        uri: foto,
        type: "image/jpg",
        name: "foto.jpg"
      });
    })
    this.props.servico.criar(formData);
    

    以及将请求发送到服务器的函数:

    criar: (servico) => {
      this.setState({carregando: true});
      axios.post(`${REQUEST_URL}/arquivos/seila/upload`, servico).then((response) => {
        this.setState({carregando: false});
        this.props.alertWithType("success", "Sucesso", "Arquivo salvo com sucesso");
      }).catch(error => {
        this.setState({carregando: false});
        this.props.alertWithType("error", "Erro", error.response.data.error.message);
      })
    },
    

    所以您不需要将内容类型头设置为多部分/表单数据,也不需要将图像转换为blob,实际上您只需要每个图像的uri,我认为Type和name属性是可选的。

    推荐文章