首页 > 解决方案 > 如何在拍照后立即将照片传输到 x-www-form-urlencoded EXPO

问题描述

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

拍摄当前图片,保存在相册中,查看uri是没有问题的。

但是x-www-form-urlencoded发送过程不能正常工作。

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

邮递员也附上。(邮递员没有问题。)

 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!')
      });
  };

邮递员标题

邮递员身体

标签: react-nativeexpoimage-uploadingreact-native-camerax-www-form-urlencoded

解决方案


附加到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


推荐阅读