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

How can I style the empty text in an ExtJS grid using CSS?

Is there a specific CSS class for a grid's emptyText? After inspecting the element with Firebug, all I found was: <div id="gridview-1021" class="x-component x-grid-view x-fit-item x-component-default x-unselectable" role="presentation" tabindex=" ...

Tips on embedding a textField into a designated row within a table by clicking a button with the help of reactjs and material ui

I need assistance adding multiple text fields to a specific row within a table when a designated row's "add" button is clicked. Currently, I am able to add a text field when the button is clicked, but it adds the text field to every row in the table. ...

What is preventing my boolean from being altered?

Creating a basic calculator that can handle single-digit arithmetic. The current code is incomplete and redundant, so please avoid commenting on that. <!doctype html> <html> <head> <title>JavaScript Learning Zone</title> ...

Unable to alphabetically arrange buttons automatically

I am encountering a challenge with automatically sorting buttons alphabetically on my webpage. I am unable to determine the method for sorting these buttons using jquery or javascript, but my goal is to have them sorted automatically when the page loads. I ...

Utilizing PUG for Iterating Through Multiple Items in Express Framework using JSON Data

I'm currently working on a small application using Express and PUG, aiming to achieve the following: https://i.stack.imgur.com/ZDyTK.png index.pug ul#restaurants-list li img.restaurant-img(alt='Mission Chinese Food', sr ...

Utilizing React SSR to dynamically import components based on API response

I am currently working on a SSR React app using the razzle tool, with the server running on the express framework. My goal is to dynamically load React components based on the value included in an API response. My folder structure looks like this: views ...

Decomposition of words in VueJS based on numerical values

Is there a way to handle word declension based on the number of items in VueJS? For example, displaying "0 skins", "1 skin", "2 skins", "3 skins", "4 skins", "5 skins", and so on. I currently have a basic code snippet with hardcoded text: <div class=&q ...

The Discord OAuth2 bot fails to assign roles to authenticated users

While working on OAuth2 login for my website, I encountered an issue. After a user successfully logs in through OAuth2, the bot should assign a role to them on my Discord server. However, when I tested the login process myself, the bot returned an error me ...

Numerous Data Tables on a single page with varying parameters

I'm facing a scenario where I have two dataTables on the same page. Referencing this example: https://datatables.net/examples/basic_init/multiple_tables.html Everything seems to be working fine, but both tables share common parameters such as buttons ...

Ensuring that $http.put() sends properly structured data as opposed to a JSON object

After spending some time, I managed to create a custom API for a personal project. To ensure its functionality, I used the Postman add-on for Chrome to simulate PUT and DELETE requests. This process revealed PHP's limitations when handling these types ...

Optimizing Variable Destructuring Efficiency

Is there a difference in performance when assigning variables like const color = props.color; compared to destructuring like this const { color } = props; Furthermore, does destructuring within the parameters affect performance positively or negatively ...

AngularJS webpage displays an error message stating: "fn is not a function, Uncaught TypeError"

Hello, I am new to AngularJS and trying to understand the following code snippet: (function () { getDataFactory = function () { return { callWebApi: function (reqData) { alert(reqData); } ...

A method to use jQuery to replace newlines with commas in user input

Input Processing Challenge <input> Whenever there is multi-line text pasted into the input field, I need to replace newlines (\r, \n, and \r\n) as well as tabs \t with commas ,. This scenario mainly occurs when users copy c ...

Tips for Removing Copyright on Charts

Check this out : https://jsfiddle.net/oscar11/4qdan7k7/5/ Is there a way to eliminate the phrase JS chart by amCharts? ...

Display buttons when hovering with React

Seeking assistance with implementing functionality in a React application where buttons for editing and deleting display only when the mouse hovers over the corresponding row. Currently, the implemented code displays these buttons in all rows on hover. Sn ...

Having trouble getting the video to load on your Mozilla Firefox browser?

Unable to play video on Firefox. Error message: URL.createObjectURL(video): Error decoding media resource blob: NS_ERROR_DOM_MEDIA_FATAL_ERR (0x806e0005) Details: Decoder may not support the requested video format with YUV444 chroma subsampling. Tried usi ...

Issues encountered while optimizing JSON file in a ReactJS program

I'm struggling with utilizing Array.prototype.map() in Javascript Specifically, I'm reformatting a JSON file within my react app, which looks like: { "id": 1, "title": "Manage data in Docker", "description": "How to use v ...

How can PHP be used to decode JSON and transmit it to Javascript?

I am aiming to utilize the Twitter API in order to dynamically populate slides on a webpage with recent tweets without needing to refresh the entire page. Currently, my approach involves making an AJAX call every few seconds from a JavaScript function on ...

How can I prevent the <br/> tag from being included on every new line when exporting data to PDF in jQuery Datatable?

I am currently working with a datatable that contains a large amount of data. Within this table, I have included 2 buttons for exporting the data in PDF and CSV formats. One of the columns within my table contains a comma-separated string, and when I expor ...

linking to a page that shows the user's chosen option from a dropdown menu

One of the challenges I encountered was creating a feature that allows users to share a specific selection from multiple dropdown lists on a page. Essentially, my goal was to enable users to send a link that would direct others to the same page with the ex ...