Как отправить POST-запрос с файлами вact-native android - PullRequest
0 голосов
/ 04 мая 2020

Я пытаюсь отправить файл с нативным кодом 62.2 с запросом на выборку, когда я выбираю файл, мой массив заполнения такой ->

{"data": ~blob image data~,"fileName": "Screenshot_20200504_082033.jpg", "fileSize": 347275, "height": 1544, "isVertical": true, "originalRotation": 0, "path": "/storage/emulated/0/DCIM/Screenshots/Screenshot_20200504_082033.jpg", "timestamp": "2020-05-04T02:50:33Z", "type": "image/jpeg", "uri": "content://media/external/images/media/126441", "width": 720}

Я использую библиотеку для выбора данные react-native-image-picker

отправляемый мной запрос на выборку будет выглядеть следующим образом

var picForm = new FormData();
          picForm.append('userId', userId);
          picForm.append('file', source) // <- this is the main data
fetch(API_HOST + 'user/profilePictureUpload', {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'multipart/form-data',
              Authorization: 'Basic jfjsfhsjkfhsjkjksksjjksfjkskfksdd',
              Authorizationkeyfortoken:''fjsfsfjsfsjhfsjkfhjksfjksfjsf,
            },
            body: picForm,
          }).then(res => res.text()).then(text => console.log(text)).catch(e => console.log(e));

для этого кода я получаю сообщение об ошибке source is [TypeError: Network request failed], когда я попробуйте это

    var picForm = new FormData();
              picForm.append('userId', userId);
              picForm.append('file', {
  uri: source.uri, //<- content://media/external/images/media/126441
  type: 'image/jpeg',
  name: source.fileName //<- Screenshot_20200504_082033.jpg
})

для этого кода я получаю сообщение об ошибке source is [TypeError: Network request failed]

var picForm = new FormData();
          picForm.append('userId', userId);
          picForm.append('file', source.files[0]) // <- this is the main data

ошибка появляется неопределенный объект

 var picForm = new FormData();
              picForm.append('userId', userId);
              picForm.append('file', 'files') // <- this is the main data

сеть верна, но это не то, что я хочу отправить, это простая строка. Ребята, вы не знаете, как отправить файл с запросом на выборку

Ответы [ 2 ]

0 голосов
/ 05 мая 2020

Этот код отлично работает для меня при загрузке нескольких изображений, с описанием фотографии и идентификатором пользователя, а также статусом прогресса

constructor() {
    super();
    this.state = {
      uploadPercentage: 0,
    }
  }

  // upload Files upload_Files = async () => {
  upload_File() {

    if (this.validate_Fields()) {
      const { image, images, files, description, userId, size } = this.state;
      console.log('AddPost Screen : upload_File:', 'userId:', userId, 'Files:', files, 'description:', description)
      // this.setState({ error: '', loading: true });

      if (this.state.type === 'image/jpeg') {

        console.log('AddPost Screen : upload_ files :', files);
        const formData = new FormData();
        formData.append('user_id', userId);
        formData.append('description', description);
        // formData.append('files[]', files);
        for (let i = 0; i < files.length; i++) {
          formData.append('files[]', {
            name: files[i].path.split('/').pop(),
            type: files[i].mime,
            uri: Platform.OS === 'android' ? files[i].path : files[i].path.replace('file://', ''),
          });
        }


        // upload percentage progress bar  ******************************************************
        const options = {
          onUploadProgress: (progressEvent) => {
            const { loaded, total } = progressEvent;
            let percent = Math.floor((loaded * 100) / total)
            console.log(`${loaded}kb of ${total}kb | ${percent}%`);

            if (percent < 100) {
              this.setState({ uploadPercentage: percent })
            }
          }
        }


        axios.post(API_URL + '/fileuploadapi/uploadPost', formData, options, {
          headers: { "Content-type": "multipart/form-data" }
        }).then((response) => {
          console.log(JSON.parse(JSON.stringify(response.status)));


          // upload percentage progress 
          this.setState({ uploadPercentage: 100 }, () => {
            setTimeout(() => {
              this.setState({ uploadPercentage: 0 })
            }, 1000);
          })


          this.cleanupImages();

          Alert.alert('Upload Post Successfully');
        }).catch((error) => {
          console.log(error);
          this.cleanupImages();

          Alert.alert('image Upload Post Failed  , Try again !');
        });

     }
   }
}



  // clear files data 
  cleanupImages() {

    this.setState({
      description: '',
      image: null,
      images: null,
      // video: '',
      files: '',
      uploadPercentage: 0,
    })
    ImagePicker.clean().then(() => {
      console.log('removed tmp images from tmp directory');
    }).catch(error => {
      alert(error);
    });
  }

Если что-нибудь понадобится, сообщите мне

0 голосов
/ 04 мая 2020

пожалуйста, создайте объект изображения следующим образом

 var imageData = {
 uri: iamge_path,
  type: file_type, //the mime type of the file
  name: file_name
}

const data = new FormData(); 
data.append("image",imageData)

Пожалуйста, убедитесь, что тип запроса - post, а ваш бэкэнд обрабатывает данные формы правильно

...