Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic Cordova Camera Upload File using XHR instead of File Transfer Plugin

I am using Cordova Camera Plugin in Ionic 1 (Angular 1.3) and I need to upload this image to the server. Since the cordova-plugin-file-transfer is now deprecated and it is recommended to now upload the file using xhr and cordova-plugin-file, I am stuck here on how to proceed. I couldnt find any examples on this and the link I read for this did not help me on how I can upload the imageUrl gotten from Cordova Camera Plugin. This is what I have so far:

function openCamera() {
            var options = {
                  quality: 50,
                  destinationType: Camera.DestinationType.FILE_URI,
                  sourceType: Camera.PictureSourceType.CAMERA,
                  allowEdit: true,
                  encodingType: Camera.EncodingType.JPEG,
                  mediaType: Camera.MediaType.PICTURE,
                  correctOrientation: true 
            }
            var func = fileTransfer;

            navigator.camera.getPicture(function cameraSuccess(imageUri) {
                console.log(imageUri);
                // Upload the picture
                func(imageUri);

            }, function cameraError(error) {
                console.debug("Unable to obtain picture: " + error, "app");

            }, options);
}

function fileTransfer(imageUri) {
          window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
              console.log('file system open: ' + fs.name);
              fs.root.getFile(imageUri, { create: true, exclusive: false }, function (fileEntry) {
                  fileEntry.file(function (file) {
                      var reader = new FileReader();
                      reader.onloadend = function() {
                          // Create a blob based on the FileReader "result", which we asked to be retrieved as an ArrayBuffer
                          var blob = new Blob([new Uint8Array(this.result)], { type: "image/jpg" });
                          var oReq = new XMLHttpRequest();
                          var server = 'http://serverurl.com/upload.php';
                          oReq.open("POST", server, true);
                          oReq.onload = function (oEvent) {
                              // all done!
                          };
                          // Pass the blob in to XHR's send method
                          oReq.send(blob);
                      };
                      // Read the file as an ArrayBuffer
                      reader.readAsArrayBuffer(file);
                  }, function (err) { console.error('error getting fileentry file!' + JSON.stringify(err)); });
              }, function (err) { console.error('error getting file! ' + JSON.stringify(err)); });
          }, function (err) { console.error('error getting persistent fs! ' + JSON.stringify(err)); });
}

I understand the fileTransfer() is wrong here since I have just used what I read in the link and I cant expect to magically work. I have no idea on how I can use the imageUrl I got from navigator.camera.getPicture and upload it using Ajax in Angular 1.3.

The above code fails in error getting file! {"code":5}.

Can someone help me please?

like image 489
Neel Avatar asked Oct 17 '22 21:10

Neel


2 Answers

Instead of using file path you can try below solution.

function b64toBlob(b64Data, contentType, sliceSize) {

        contentType = contentType || '';
        sliceSize = sliceSize || 512;

        var byteCharacters = atob(b64Data);
        var byteArrays = [];


        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);

            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {

                byteNumbers[i] = slice.charCodeAt(i);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

        var blob = new Blob(byteArrays, { type: contentType });
        return blob;
    }
like image 97
Paresh Gami Avatar answered Oct 21 '22 06:10

Paresh Gami


Check your fileUri.

If file's path have tmp like file:///var/mobile/Containers/Data/Application/.../tmp/cdv_photo_003.jpg

You have to use LocalFileSystem.TEMPORARY

Because, this image exists in temporary path.

window.requestFileSystem(
  LocalFileSystem.TEMPORARY,
  0,
  (fs) => {
    console.log('file system open: ' + fs.name)
    fs.root.getFile(
      fileName,
      { create: true, exclusive: false },
      (fileEntry) => {
        fileEntry.file(
          (file) => {
            const reader = new FileReader()
            reader.onloadend = async () => {
              const formData: FormData = new FormData()
              const blob = new Blob([new Uint8Array(reader.result as any)], { type: 'image/png' })
              formData.append('file', blob)
              await this.http.post('http://apiurl', formData)
            }
            // Read the file as an ArrayBuffer
            reader.readAsArrayBuffer(file)
          },
          function (err) {
            console.error('error getting fileentry file!' + err)
          }
        )
      },
      function (err) {
        console.error('error getting file! ' + err)
      }
    )
  },
  function (err) {
    console.error('error getting persistent fs! ' + err)
  }
)
like image 23
junho Avatar answered Oct 21 '22 06:10

junho