Steps to retrieve a base64 image using Cordova's FileTransfer feature

Recently, I encountered an issue with downloading base-64 images using the Cordova file transfer protocol. When I tried to provide a remote server path like "", the download worked perfectly. However, when I attempted to use a base-64 image path for the filepath, it failed to download.

----Here is a snippet of my code----

  function download(){
        var imageData = image.src;
        imageData = imageData.replace('data:image/png;base64,', '');

        var d = new Date();
        var imageName = "sample" + d.getTime() + ".png";

        //var filepath = encodeURI("https://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png");
        var filepath = encodeURI(imageData);

        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
            fileSystem.root.getFile(imageName, { create: true, exclusive: true }, function (fileEntry) {
                // get the full path to the newly created file on the device
                var localPath = fileEntry.fullPath;

                // massage the path for android devices (not tested)
                if (device.platform === "Android" && localPath.indexOf("file://") === 0) {
                    localPath = localPath.substring(7);
                }

                // download the remote file and save it
                var remoteFile = filepath;
                var fileTransfer = new FileTransfer();
                fileTransfer.download(remoteFile, localPath, function (newFileEntry) {
                    // successful download, continue to the next image
                    console.log('successful download');
                },
                function (error) { // error callback for #download
                    console.log('Error with #download method.', error);
                });
            });
        })

    })
}
}

If anyone has insight or expertise in base-64 conversion, your help would be greatly appreciated. Thank you in advance!

Answer №1

I successfully resolved my query through innovative methods.

Initially, I transformed a base64 image into a file stream, established an image on the server via web services, uploaded the image to the server, retrieved the server path, and then utilized cordova filetransfer for downloading.

Here is my implementation:

=> Web service implementation for converting base64 image to image

string imageDataString = imageData.imageData;
   string fullPathName = "d:\\uploadimages";
   FileStream fileStream = new FileStream(fullPathName, FileMode.Create);
   BinaryWriter binaryWriter = new BinaryWriter(fileStream);

   byte[] imageDataBytes = Convert.FromBase64String(imageDataString);

   binaryWriter.Write(imageDataBytes);
   binaryWriter.Close();

=> Downloading image on mobile device

function download()
{
    var filePath = encodeURI("http://www.telerik.com/sfimages/default-source/logos/app_builder.png"),
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
                fileSystem.root.getFile("sample.jpg", { create: true, exclusive: false }, function (fileEntry) {

                    // obtain the full path to the newly created file on the device
                    var localFilePath = fileEntry.fullPath;

                    // adjust the path for Android devices (untested)
                    if (device.platform === "Android" && localFilePath.indexOf("file://") === 0) {
                        localFilePath = localFilePath.substring(7);
                    }

                    // download the remote file and store it
                    var remoteFile = filePath;
                    //loadingOverlay.displayLoading("Image will be saved on your device.");

                    var fileTransfer = new FileTransfer();
                    fileTransfer.download(remoteFile, localFilePath, function (newFileEntry) {
                        // successful download, proceed to the next image
                        var downloadedImagePath = newFileEntry.fullPath;
                       console.log('successful download');
    
                    },
                    function (error) { // error callback for #download
                        console.log('Error with #download method.', error);
    
                    });
                });
                function(error) { // error callback for #getFile
                    console.log('Error with #getFile method.', error);
                });

            })
}

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

Enhance your Wordpress posts with a custom pop-up form for each individual button

On a page, there are various custom posts being displayed with the post type 'property', each containing a button: <button class="btn btn-primary">Submit Offer</button> This button is looped and shown below every post. What ...

Updating an array within an object using JSON

Check out the structure of my JSON response: "_id" : 537, "quizzes" : [ { "wk" : 1, "score" : [ 10 ] }, { "wk" : 2, "score" : [ 8 ...

Activate session capabilities within custom role and membership providers

I have developed custom role and membership providers for my ASP.NET 4 project without using MVC. You can see the implementation details in this Project. To configure authentication, I have added the following code in my web.config: <authentication mo ...

Swap Text/Characters When Hovered Over

I'm looking to add a fun interactive element to my webpage where the letters in certain text rearrange when a user hovers over it. For instance, hovering over "WORK" would display "OWKR" instead. I have a feeling that some JavaScript is needed for thi ...

Changing the `$location.path` updates the URL without triggering a redirect

When I try to redirect to another page by clicking a button or a link, the URL changes but the redirection doesn't happen. I have to manually refresh the page with the new URL. I'm not sure if the issue lies in the module or the controller. loca ...

contenteditable -- Utilizing AngularJS to create a block element for the title only

When I click on an input field that is editable, I want the background color to change to white within the box. Can someone please assist me with this? Below is my code: HTML <div id="section{{section.index}}"> <h2 class="title" contentedit ...

Accessing new information seamlessly without the need for page refresh

For optimal mobile viewing of my website, I am considering implementing a select element. Here are the available options: HTML: <select name="select-choice-8" id="select-choice-nc"> <optgroup label="News"> & ...

Why doesn't Mongoose automatically generate an _id for my array elements when I push them in?

I am looking for a way to have mongoose automatically add an _id field to the objects I push into my array. Here is my mongoose schema: var playerModel = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "Users", }, cl ...

Here's a way to run JavaScript code from a <script> tag included in an AJAX response

Currently, I am making a jQuery GET request in this format: $.get($(this).attr("href"), $(this).serialize(), null, "script"); I'm expecting the response to be enclosed in script tags. I know that the browser won't run the response if it contai ...

Exploring Shader Materials and OpenGL Framebuffers within the realm of THREE.js

In my current project, I am attempting to utilize an FBO within a material in THREE.js. The project involves a GPU-based fluid simulation that generates its final visualization to a framebuffer object, which I intend to use as a texture for a mesh. Below i ...

Is it recommended to utilize addEventListener?

Is it better to use the addEventListener method in these scenarios? <input id="input" type="file" onchange="fun()> or document.getElementById("input").addEventListener("change", function() { fun(); }); What are the advantages of using one over ...

eliminating items from an array nested inside another array

****************UPDATED********************************************************* I am stuck trying to manipulate an array within another array and remove elements based on conditions. The main goal is to make changes without altering the original array of ...

Exploring the World of 3D Rotation with Three.js

I currently have 2 mesh objects - the Anchor and the Rod. The Anchor rotates around the z-axis, as shown in the image. The Rod is designed to only move backward and forwards. You can view the image here: . However, I am struggling to determine the matrix ...

Tips for adjusting line placement on a leaflet map

My leaflet map displays two lines, but sometimes they appear identical, causing the map to show only one line due to overlap. To address this issue, I am attempting to shift one of the lines slightly so that both are visible on the map. One method I cons ...

Creating a standard Modal component in Angular

I am trying to create a versatile Modal component. When the user clicks on the Add button, I want the modal to open with the functionality to add new content. Similarly, when the user clicks on the Edit button, I want the same modal to display edit functio ...

Delete an element once the ajax request is complete

After closing the modal, I noticed that a div element was left behind causing the screen to become unresponsive. <div class="modal-backdrop fade show"></div> I found that removing this element using the console command below fixed the issue: ...

Is it allowed to use any AngularJS directives within other directives?

I am trying to create a directive that will display a list of objects from my controller. Inside this directive, I want to be able to use one of several possible sub-directives, but the specific one to be used may vary. If I set the sub-directive name in t ...

Tips for encoding AngularJS ng-model in real-time

Recently, I embarked on a new project and wanted to incorporate some AngularJS magic. The only obstacle is my limited expertise in AngularJS or JavaScript, making it difficult for me to figure out how to make it work. One key requirement is that the functi ...

Guide to setting up value observation in React Context for optimal functionality

Imagine a scenario where there is a Parent Component that provides a Context containing a Store Object. This Store holds a value and a function to update this value. class Store { // value // function updateValue() {} } const Parent = () => { const ...

Adjust the default color for the icon in the v-text-field type=date using Vuetify

I need to filter records between two dates, displaying data retrieved from the backend. Instead of following the traditional method outlined in Vuetify's date pickers documentation or using the CodePen example: Vuetify v-text-field Date Picker on Cod ...