Generate a JavaScript File/Blob from an image's URI

Can I generate a File or Blob object from an image URI?

I am utilizing the Cordova Image Picker plugin in my mobile application to retrieve photo URIs like this: "file:///data/user/0/..../image.jpg"

However, I am struggling to create a File or Blob object that Google Firebase requires for uploading my images. No matter what solution I attempt, it always seems incorrect. As a newcomer to JavaScript, I appreciate any guidance. Thank you!

Answer №1

Check out a question I posted some time ago about dealing with videos on the same topic: Uploading video to firebase (3.0) storage using cordovaFileTransfer

To handle this, you'll need to utilize cordova's file plugin to read as an arrayBuffer and then convert it into a blob. Here's an example:

var file_path = "root/to/directory";
var name = "filename.jpg";

$cordovaFile.readAsArrayBuffer(file_path, name)
    .then(function (success) {
        console.log(success);

      var blob = new Blob([success], {type: "image/jpeg"});

      console.log(blob);

      var uploadTask = storageRef.child(name).put(blob);

      uploadTask.on('state_changed', function(snapshot){
          var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          console.log('Upload is ' + progress + '% done'); 

      }, function(error) {
          console.log("Error uploading: " + error)
      }, function() {
          var downloadURL = uploadTask.snapshot.downloadURL;
          console.log("Success!", downloadURL);
      });

    }, function (error) {
        console.log("Failed to read file from directory, error.code);

    }

If your program provides you with the full path to the image, remember to extract the file name by looking for everything after the final /

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

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

What is the reason border property does not transition effectively?

I am trying to remove the border property after a certain period of time (1 second) and make it smooth. Here is what I have attempted: var elem = $('div').css({'border-top':'6px solid #FC9A24', 'border-le ...

Iterating through an object in Javascript using dynamically changing property names

Is there an efficient way in Javascript to iterate through the property names of objects in an array? I have objects with properties from guest1 to guest100. Instead of manually looping through each property, is there a method to loop through all the gues ...

Encountering a problem when trying to utilize material-ui icons in a React application

After installing the Material-UI core and icons packages using npm install @material-ui/core and npm install @material-ui/icons in my React app, I tried to use the FileUploadIcon. Here's how I imported it: import { FileUploadIcon } from '@materia ...

Issue with Photoswipe pswp class Not Getting Properly Cleared Upon Closing Image

My website has a Photoswipe image gallery from . The issue I'm facing is that the CSS class does not reset or clear after closing the gallery for the second time. For example, when a user opens item 1, the images are loaded into the picture div via A ...

Vue Component Unit Testing: Resolving "Unexpected Identifier" Error in Jest Setup

Having just started using Jest, I wanted to run a simple unit test to make sure everything was set up correctly. However, I encountered numerous errors during compilation while troubleshooting the issues. When running the test suite, Jest successfully loc ...

The Vue 3 router seems to be malfunctioning and I am quite puzzled as to why

As someone new to Vue (specifically Vue 3), I decided to test a mock Vue application. After successfully testing the default homepage, I wanted to explore creating multiple pages. Despite following tutorials step by step, I've encountered an issue whe ...

The JSON.parse function encounters issues when trying to parse due to a SyntaxError: Unexpected character found after JSON at position 2, causing it to be unable

I've encountered an issue with my JavaScript code when trying to retrieve the value of the details field from JSON data. While all other values are successfully passed to their respective fields, the details field generates the following error: "Unabl ...

Adjust the size of the font in accordance with the value of the span text

I am looking to adjust the font size based on the value within the span element. The numbers in the class name may vary. Issue: using text() retrieves all values (e.g. 50020) I want to incorporate each() and $this in some way. How can I do this? Thank ...

Can a value of a variable be "stored" in NodeJS?

I am working on a website that allows clients to make their site go live by setting var live = true;. Once this variable is set, certain webpages will display. I would prefer not to store the live variable in a database as creating a collection solely fo ...

JavaScript's Ajax POST request to PHP is not functioning as expected

My current code setup involves handling $_GET[] requests on the products.php page by passing them to get_data_products.php via an ajax POST request. The data retrieved from get_data_products.php is then displayed accordingly. PHP if(isset($_GET['cat ...

Checking email existence through remote jQuery validation

Utilizing the jQuery validator plugin, I am implementing an ajax function with a remote method to validate whether an email already exists in my database. However, I am encountering an error when making the ajax call within my validation function. "email ...

Dealing with VueJS - Sharing an array of data from a child to a parent component using v-model

I am facing an issue in emitting data (array) from a child component to a parent component using v-model. However, when the parent component is created, my console.log does not work. I am hesitant to work with Vuex as I am still a beginner. Here is my chi ...

Sending a JavaScript function as part of an ajax response

I'm currently working on a system where the user can submit a form through AJAX and receive a callback in response. The process involves the server processing the form data and returning both an error message and a JavaScript function that can perform ...

Automatically switch Twitter Bootstrap tabs without any manual effort

Is there a way to set up the Twitter Bootstrap tabs to cycle through on their own, similar to a carousel? I want each tab to automatically switch to the next one every 10 seconds. Check out this example for reference: If you click on the news stories, yo ...

Ways to automatically check a checkbox using jQuery

Is there a way to use jQuery to programmatically click a checkbox? I am trying to create a hidden checkbox that will be checked when a user clicks on a specific element, but my current code is not functioning as expected and I am unsure why. You can view ...

What is the purpose of uploading the TypeScript declaration file to DefinitelyTyped for a JavaScript library?

After releasing two JavaScript libraries on npm, users have requested TypeScript type definitions for both. Despite not using TypeScript myself and having no plans to rewrite the libraries in TypeScript, I am interested in adding the type definition files ...

What could be causing my insertRow function to inject empty cells into my table?

I am facing an issue with adding the results of a fetch request into a table as a new row. Strangely, when I click the button to trigger this function for the first time, it adds an empty row instead of the desired data. However, on subsequent clicks, the ...

Create an instance using the window object in JavaScript

Having an issue when trying to instantiate a class using the window object. I have a namespace called UTIL and within it, there is a class defined as follows: var UTIL = { Classes : {}}; UTIL.Classes.ObservationVal = function(state, id, type, context, pe ...

What is the Proper Way to Import Three.js Modules in a Vue Application?

My goal is to utilize three.js for displaying a gltf file. To achieve this, I need to import the GLTFLoader module from the three.js node package. As per the documentation, the correct way to import it is: import { GLTFLoader } from 'three/examples/ ...