importing files from Uploadcare using ngCordova MediaFile

I am facing an issue while attempting to upload a sound file from ngCordova's $cordovaCapture service to UploadCare. The `uploadcare.fileFrom('object')` function is failing with an 'upload' error even though I have set the public key correctly. Interestingly, I am able to successfully upload the file by using a <input type="file"> tag and accessing it through `document.getElementById('fileTag').files[0]`.

$cordovaCapture.captureAudio()
                    .then(function (audioData) {

                        return uploadcare.fileFrom('object', audioData[0])
                            .done(function (fileInfo) {
                                console.log(fileInfo);

                            }).fail(function (err) {
                                console.log(err);

                            })
                    })

The structure of the `audioData[0]` object is as follows:

MediaFile {
    end:0
    fullPath:"file:/storage/emulated/0/Sounds/Voice%20002.m4a"
    lastModified:null
    lastModifiedDate:1481324751000
    localURL:"cdvfile://localhost/sdcard/Sounds/Voice%20002.m4a"
    name:"Voice 002.m4a"
    size:49227
    start:0
    type:"audio/mpeg"
} __proto__:File

I suspect that the issue might be due to the fact that the object is a MediaFile instead of a File. I would appreciate assistance on how to properly cast one into the other.

FileEntry
    filesystem:FileSystem
    fullPath:"/Sounds/Voice 002.m4a"
    isDirectory:false
    isFile:true
    name:"Voice 002.m4a"
    nativeURL:"file:///storage/emulated/0/Sounds/Voice%20002.m4a"
    __proto__:Entry


File
    end:49227
    lastModified:1481324751000
    lastModifiedDate:1481324751000
    localURL:"cdvfile://localhost/sdcard/Sounds/Voice%20002.m4a"
    name:"Voice 002.m4a"
    size:49227
    start:0
    type:"audio/mpeg"
    __proto__:Object

After using window.resolveLocalFileSystemUrl(), you obtain the above FileEntry object which gives rise to the correspondent File object. However, despite this conversion, UploadCare still throws an "upload" error.

Answer №1

To upload audio files to uploadcare using ngCordova $cordovaFileTransfer(), follow the code snippet below:

var fileName = filePath.split('/').pop();
var uploadcareOptions = {
    fileKey: "file",
    fileName: fileName,
    chunkedMode: false,
    mimeType: 'audio/mp4',
    params: {
        "UPLOADCARE_PUB_KEY": "upload-care-public-key",
        "UPLOADCARE_STORE": 'auto',
        fileName: fileName
    }
};
return $cordovaFileTransfer.upload('https://upload.uploadcare.com/base/', filePath, uploadcareOptions)

Remember to specify the mime type as 'audio/*' when sending audio files, or else uploadcare will assume it's an image.

Answer №2

Utilize uploadcare.fileFrom to transfer a file from a native file object. Give this code snippet a shot:

window.resolveLocalFileSystemURL(imageData[0].localURL,function(fileEntry){
    fileEntry.file(function(file) {
        uploadcare.fileFrom('object', file);
        ...
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Styling a table based on specific conditions using Angular and JavaScript

I am trying to conditionally style the text in the table based on the time elapsed since the last ping. Specifically, I want to change the color of the text from green to red once 5 minutes have passed and vice versa. <form name="myform" data-ng-submit ...

Ways to ensure text fits nicely within a container: HTML & CSS

Below is a code snippet: @import url('https://fonts.googleapis.com/css?family=Merriweather|Open+Sans'); .square { max-width: 460px; background: white; border-radius: 4px; box-shadow: 0px 5px 20px #D9DBDF; -webkit-transition: all 0. ...

Strange glitches and slow loading problems plaguing website. (GoDaddy)

TackEmporium.com Lately, I have been revamping my website, which was originally given to me by a friend. I have been making slight adjustments to update its appearance while keeping its classic look with enhanced resolution and cleaned-up HTML5 code. Rec ...

What is the method for sending a file using JavaScript?

var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg'; var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..'; var xmlhttp = getXmlHttp(); var params = 'photo=' + encodeURIComponent(photo); xmlhttp ...

The functionality for selecting text in multiple dropdown menus using the .on method is currently limited to the first dropdown

Having trouble selecting an li element from a Bootstrap dropdown and displaying it in the dropdown box? I'm facing an issue where only the text from the first dropdown changes and the event for the second dropdown doesn't work. <div class="dr ...

Guide on sending a REST request with JSON data as a parameter in AngularJS

I've spent a great deal of time searching on the internet for a clear example on this subject but have not been able to find one. What I'm looking for is a basic demonstration of how to make a REST call using AngularJS where we can pass JSON as a ...

What is the best way to execute two JavaScript functions within an inline onclick event?

I am currently working on the following code snippet: <script> function delay (URL) { setTimeout( function() { window.location = URL }, 2000); }</script> And then I have the following within the <body> element: <img src="small_rabbi ...

Providing secure access to Apostrophe-CMS S3 assets and attachments via HTTPS

Currently, I am utilizing Amazon S3 to deliver both my static assets and user uploads within the context of apostrophe-cms. While my site is loading via https, all of my assets appear to be loading using http. I have set up a cloudfront distribution at th ...

JavaScript error: Cannot read property 'str' of undefined

I'm attempting to retrieve specific values from a JSON array object, but I encounter an error message. var i = 0; while (i < n) { $.get("counter.html").done(function (data2) { var $html = $("<div>").html(data2); var str = ...

Ionic datetime returns default values upon initialization

I'm currently in the process of developing an Ionic-Angular-app. I require a datetime component on a page to set the creation date of an object. I am using formGroup for this purpose, but whenever I choose a different date, it always reverts back to t ...

Troubleshooting: Issues with AngularJS Data Binding in HTML Tables

I have been working on code from an online tutorial but unfortunately, it is not functioning properly. I have checked the script, app, and controller but still cannot identify the issue. Any assistance would be greatly appreciated! ...

AngularJS: Users must click submit button twice for it to function properly

It's puzzling that I have to click the submit button on my form twice before it triggers the save function below. My HTML is written in Pug format. Below is a snippet of my HTML template: <form ng-submit="save()"> <div class="form-group" ...

Is there a way for me to retrieve $event within a directive?

I'm struggling to figure out how to pass it as an attribute! Although I can use ng-click="function($event)" to pass $event to a controller function, I really want to access it within a directive. My main goal is to be able to stopPropagation() and/o ...

Modifying the value property of the parent element

Here is an example of the HTML code I am working with: <td value='3' style='text-align: center'> <select class='selection' onchange=''> <option value='1'>1</option> <opti ...

Dynamic headers with $save in AngularJS $resource

I have been attempting to include dynamic headers in a $resource as shown below: angular.module('app') .factory('API', function ($resource, API_URL) { return { event: function(userId){ return $resource(API_URL + '/event/ ...

Ways to import JavaScript into child HTMLs embedded within ng-view

I'm diving into angular for the first time and I need to figure out how to incorporate JavaScript into my HTML within ng-view. Some suggestions I came across mention adding jQuery. Can someone provide some guidance on specifically what needs to be ad ...

Retrieving the _id of a new document in MongoDB using Node.js

I am facing a challenge understanding MongoDB after transitioning from using relational databases. Currently, I am attempting to store an image with the following code: exports.save = function ( input, image, callback) { console.log('Image P ...

IntelliJ does not support the use of newlines within Vue.js component templates

While working with Vue.js in IntelliJ IDEA, I encountered a small problem related to defining component templates. The issue is that IntelliJ seems to struggle when the template spans more than one line and attempts to concatenate them together. For examp ...

Capture all Fetch Api AJAX requests

Is there a way to intercept all AJAX requests using the Fetch API? In the past, we were able to do this with XMLHttpRequest by implementing code similar to the following: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.p ...

Improve navigation by integrating jQuery validation to resolve input errors seamlessly

I have been working with the jQuery validation plugin and Bootstrap. I recently added a fixed navigation bar at the top of the page using Bootstrap CSS. However, I encountered an issue where the fixed navigation was overlapping with the error message for i ...