Exploring cloud photos on an Android browser with the help of FileReader

This snippet of javascript code creates an image upload button and displays the uploaded image:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();            
        reader.onload = function (e) {
            $('#target').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

You can view the full jsfiddle example here.

Although this code works perfectly on most mobile browsers, it encounters a problem specifically with the stock Android browser. Images fail to load if they are stored remotely, such as those from synced Facebook or Picasa accounts. While FileReader is designed for local files, other mobile browsers like Chrome, Opera, and Firefox have no issues with loading remote images.

After checking the FileReader error code, it seems that images from Facebook/Picasa return a NOT_FOUND_ERR: https://developer.mozilla.org/en-US/docs/Web/API/FileError

This issue seems unique to the stock Android browser, as it works fine with local files and camera-captured images, but fails to load remote Facebook/Picasa images, showing icons instead of the actual photos. This anomaly has been observed on Android versions 4.3 and 4.4.

Although similar issues have been discussed online, such as this thread on Stack Overflow: Issue with stock Browser picking photos from Gallery

The issue seems to be related to the inability of FileReader to read remote files, but the fact that it works on other mobile browsers raises questions about the specific compatibility of the stock Android browser.

Answer №1

When encountering the error, there are two potential reasons behind it.

  1. The first explanation could be that the files "Images" you are attempting to read using the HTML5 API FileReader are either locked or being used by other applications such as Facebook or Picasa. In such cases, there may be nothing you can do through JavaScript unless you have physical access to the device, such as a Phone.
  2. The second explanation, which is more probable, is that certain browsers may not be able to trigger the onload event of the FileReader due to incomplete support for this HTML5 API. More information on browser compatibility can be found on the caniuse website. This issue can often be resolved by replacing the event onload with onloadend.

Here is a revised version of your code:

var reader = new FileReader(); 
reader.onloadend = function () { 
    console.log(reader.result); 
}; 
reader.readAsDataURL(file);

For an example, you can check out this jsfiddle.

You can also view a Demo of FileReader in action here.

Answer №2

    <input id="fileinput" name="arquivo[]" type="file" multiple="multiple" onchange="FileDetails()"/>
    <var id="file_List"></var>
    <button type="button" onclick="Click()">Click Me!</button>
    <script
            src="https://code.jquery.com/jquery-3.3.1.js"
            integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
            crossorigin="anonymous"></script>
    <script>
    // custom function to store file input details in memory
    G_Array         = [];
    G_Cont_Upload   = 0;
    function Click() 
    {
        var a = 1;                                      // checking the global variable content as needed
    }
    function FileDetails() 
        {
        var file_arr = [];
        if (typeof (FileReader) != "undefined") 
            {
            var files = $('#fileinput')[0].files; 
            var reader  = [];
            for (var i = 0; i < files.length; i++)
                {
                var FileDet = files[i];

                var name    = FileDet.name;
                var Size    = FileDet.size;
                var Obj     = {Name: FileDet.name, SizeInicial : FileDet.size};
                G_Array.push(Obj);

                reader[i]   = new FileReader();

                function f_ReadFile(e)
                    {
                    var content = e.target.result;
                    G_Array[G_Cont_Upload].SizeAtual = content.length;
                    G_Array[G_Cont_Upload].Content   = content;           // content base 64
                    G_Cont_Upload++;
                    }
                reader[i].onload = f_ReadFile;
                reader[i].readAsDataURL(FileDet);
                }
            } 
        else 
            {
            alert("This browser does not support HTML5 FileReader.");
            }
        }
</script>
</body>

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

Node.js: Array remains undefined despite being logged on the console

My goal is to download a CSV file, read it line by line, and add the split lines (based on ',') to the tmparray. This code successfully prints all the elements in the array. var request = require('request'); var fs = require('fs&a ...

What is the best approach to send a value to the controller?

How can I pass a value to the child controller using the stateProvider in Angular? This is what I have so far: $stateProvider .state('test', { url: '/test', views: { '': { ...

What is the best way to retrieve user interaction data in Discord.js v13?

Is there a way to retrieve the activities from interaction.options? Whenever I try using interaction.options.getUser, I encounter this error message: cannot read properties of undefined (reading 'activities') Below is the snippet of my code: con ...

Guide on altering the background color of a table row depending on the data in its cells with the help of AngularJS

I am looking to dynamically change the background color of a row based on specific cell data. If the first four characters in a table cell match a certain value, I want the entire row to change its color to red. Currently, my code changes the row color ba ...

A guide on updating a global variable using AsyncTask

My goal is to insert rows into a ListView using a customized "Location" adapter. I am attempting to include a Bitmap in each row of the ListView, sourced from a URL. To achieve this, I have a public static Bitmap variable named bitmap that I aim to update ...

preventing elements from moving unexpectedly as the navigation bar becomes fixed at the top of the page

I have a website that features a Bootstrap 3 navbar. This navbar is positioned 280px below a block div and becomes sticky at the top of the page when scrolled to that point. HTML (within < head > tags) <script> $(document).ready(function() ...

Typeahead in Angular is failing to function properly after using the $compile method

I have made some adjustments to the popover directive in order to include files and $compile them. While I've managed to make ng-repeats function properly, I'm facing issues when trying to add a typeahead feature. angular.module("app").directive ...

The HTML anchor tag paired with the italic tag is a powerful combination for

Here is some example code: <a href="#"> <i class="some-bg" /> Some Text </a> Along with some Javascript: $("a").bind("touchstart", function (e) { e.preventDefault(); console.log("Tag: " + e.target); console.log("Tag Nam ...

What is the best way to return JSON data in a compressed (gzip) format to an Ajax Request using Java?

When sending compressed JSON in response to an Ajax request from my Java program, I understand that I need to set the Content-Encoding in the Response Header to gzip. However, are there any additional steps I should take? ...

Getting inaccurate frame data using ExtractMpegFramesTest on Android?

I've been experimenting with obtaining frames using MediaCodec and came across the ExtractMpegFramesTest.java sample on this website . I managed to save the frames, but there seems to be a strange issue with their appearance. I can't quite figure ...

Encountering issues with extension CLI - "Unable to utilize the import statement outside a module"

Recently, I've been attempting to integrate the Afinn-165 node package (https://www.npmjs.com/package/afinn-165) into my Google Chrome extension. The goal is to analyze the sentiment of text scraped from each page. Being a novice in web development, I ...

Issues with JQuery .attr method not functioning as expected

I'm having trouble with the .attr() function in jQuery. It doesn't seem to be changing the background-color of the div with the id "outline" like I expected. Here's an example of my code: <div id="outline"></div> And here is t ...

Challenges with browsing navigation in Selenium WebDriver

Recently, I began my journey of learning selenium WebDriver. In an attempt to automate the task of logging into an account using the Firefox browser, I encountered a discrepancy. Manually opening the browser and clicking on the login link from the homepag ...

Using the jQuery plugin multiple times within one website

I have a decent understanding of jQuery and I'm in the process of developing a plugin. Specifically, it's a dropdown element that I'm working on. Everything functions correctly when there's only one dropdown on the site. However, when ...

Receiving a blank array upon calling res.json() in Node.js script

I'm facing an issue with my code snippet that displays all posts, including the username and display picture of each user. Everything seems to be working fine as the log output is perfect. However, I'm struggling to return this data as a JSON obj ...

Guide on implementing enums (or const) in VueJS

Seeking help on a seemingly simple task, I am trying to understand how to use "enums" in VueJS. In my file named LandingPage.js, I have the following code: const Form = { LOGIN: 0, SIGN_UP: 1, FORGOT_PASSWORD: 2, }; function main() { new Vue({ ...

Sending a function return to a React component

What I want to achieve is sending the response from an API call to a React Component and using it to generate a List. My confusion lies in how to pass the value from a function to the component. Do I require state for this process? searchMealsHandler(even ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

Incorporating an array of JSON into a Mongoose schema in JavaScript

I am currently developing an Android App focused on baseball, and I have decided to use MongoDB to store my data. The format in which I would like my JSON data stored in the database is as follows: {"<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

How to Use an Object Created from a Different Class in TypeScript

Scenario In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code: user: ...