Sufyan

Upload Image File React native (Using Fetch API)

Apr 11th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. _uploadFile = function(url, path, extra_data) {
  2.     return new Promise ((resolve, reject) => {
  3.         console.log("URL:", url, "Path: ", path, "Data: ", extra_data);
  4.  
  5.         const data = new FormData();
  6.        
  7.         if (path !== '') {
  8.             const _type = mime.getType(path);
  9.             const _ext = mime.getExtension(_type);
  10.             data.append('ext', _ext); // you can append anything.
  11.             data.append('file', {
  12.                 uri: path,
  13.                 type: _type, // or photo.type
  14.                 name: 'testPhotoName'
  15.             });
  16.         }
  17.         data.append('extra_data', JSON.stringify(extra_data));
  18.        
  19.         console.log("DATA: ", data);
  20.         fetch(Base.API_BASE_URL + url, {
  21.             method: 'post',
  22.             body: data
  23.         })
  24.         .then((response) => response.json())
  25.         .then(resp => {
  26.             console.log(resp);
  27.             resolve(resp);
  28.         })
  29.         .catch(err => {
  30.             console.log("[uploadFile] [Catch] : ", err);
  31.             reject(err);
  32.         });
  33.     });
  34. }
  35.  
  36.  
  37. //EditProfile
  38.         async pickImage() {
  39.             if (this.state.is_editable) {
  40.  
  41.                 ImagePicker.openPicker({
  42.                     width: 300,
  43.                     height: 400,
  44.                     cropping: true
  45.                 }).then(result => {
  46.                     let data = {
  47.                         user_id: this.state.user.id
  48.                     };
  49.                     uploadFile('change_profile', result.path, data)
  50.                         .then(resp => {
  51.                             if (resp.status === 'success') {
  52.                                 console.log("RESPONSE: ", resp);
  53.                                 this.setState({ user: resp.data });
  54.                                 setItem('user', resp.data);
  55.                             } else {
  56.                                 showErrorToast(resp.message);
  57.                             }
  58.                         })
  59.                         .catch(err => {
  60.                             console.log("ERROR = ", err);
  61.                         });
  62.                 });
  63.                
  64.                
  65.             }
  66.         }
Add Comment
Please, Sign In to add comment