【问题标题】:How to transfer photos to x-www-form-urlencoded immediately after taking a picture EXPO如何在拍照后立即将照片传输到 x-www-form-urlencoded EXPO
【发布时间】:2020-02-19 01:41:03
【问题描述】:

我想拍照,将其保存到相册并立即发送图像。 (不要从相册中选择。

拍摄当前图片,保存到相册,查看uri没有问题。

x-www-form-urlencoded 发送过程无法正常工作。

我认为发送API的格式可能有问题。

邮递员也附上。 (在 Postman 中没问题。)

 takePictureAndCreateAlbum = async () => {
    const { uri } = await this.camera.takePictureAsync();
    console.log('uri', uri);
    const asset = await MediaLibrary.createAssetAsync(uri);
    console.log('asset', asset);

    const filename = asset.filename;

    MediaLibrary.createAlbumAsync('Expo', asset)

      // POST API
      .then(() => {

        var file = new FormData();
        file.append({file: uri});

        return fetch(/* API_URL */, { 
              method: 'POST',
              headers:{

                  'Content-Type':'application/x-www-form-urlencoded',
                  'Accept': 'application/json'
             } , body : file} )

         .then((response) => response.text())
              .then((responseData) => {
                  console.log(responseData);
              })
              .done();

      })
      .catch(error => {
        Alert.alert('An Error Occurred!')
      });
  };

Postman Header

Postman Body

【问题讨论】:

    标签: react-native expo image-uploading react-native-camera x-www-form-urlencoded


    【解决方案1】:

    当附加到FormData 实例时,第一个参数是字段名称(您的服务器将作为此文件的对象键获取的内容),第二个参数是以下形式的对象:

    {
      uri: // The uri you received from the camera,
      type: // The file type (i.e.: image/png),
      name: // The file name
    }
    

    在你的情况下,它会是这样的:

    // Split the uri by `.` (periods)
    const uriParts = uri.split('.');
    // Grab the file type at the end of the uri
    const fileType = uriParts[uriParts.length - 1];
    
    file.append('picture', {
      uri,
      type: `image/${fileType}`,
      name: 'FILE-NAME.${fileType}`
    });
    

    另外,发送文件时,Content-Type 标头应为multipart/form-data

    【讨论】:

    • @bongjuri1551 请与我的建议分享您的代码。
    • var file = new FormData(); const uriParts = uri.split('.'); const fileType = uriParts[uriParts.length - 1]; file.append('图片', { uri, type: image/${fileType}, name: FILE-NAME.${fileType} });
    • fetch(http://52.231.70.40/api/file/uploadReceipt/${ids.id}/${ids.loginId}, { method: 'POST', headers: { 'Content-Type': 'multipart/form-data' }, body: file }) .then((response) => response.text()) .then((responseData) => { console.log(responseData); console.log('file',file) }) .done(); })
    • 错误为 400,所需的请求部分“文件”不存在 @Nick Rameau
    • @bongjuri1551 抱歉,不是要您将其发布在 cmets 中,而是要更新您的问题。
    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 2015-12-28
    • 2020-08-12
    • 1970-01-01
    • 2016-04-13
    • 2018-06-11
    • 2015-08-16
    • 1970-01-01
    相关资源
    最近更新 更多