The Power of JavaScript FileReader Unleashed

One of the features on my website allows users to upload images using a FileReader. Here's the code snippet that handles the file reading:

$("input[type='file']").change(function(e) {

    var buttonClicked = $(this);

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
            img.src = reader.result;                

            console.log(reader.result);

        }
        reader.readAsDataURL(file);
    }
});

Everything was running smoothly until I attempted to print out the result. When I tried it with a sample image from this link, https://i.sstatic.net/7svQa.jpg, the console logged over 95000 characters.

The size of this particular image is similar to the ones that will be uploaded by users. My plan was to store these images in a database but I'm concerned about how to handle such lengthy image paths. Is there a way to shorten them or obtain the image path differently?

I'm also curious as to why the image URLs are excessively long. Any tips on efficiently storing images (considering hundreds per user and over 500 users) would be greatly appreciated!

Thank you-

Answer №1

Save the Documents as Files.

There are very few scenarios where the toDataURL() method of the FileReader is necessary, so before using it, consider why you actually need it.

In your situation:

  • To showcase the image on the webpage. Instead of using a FileReader, create a direct link to the file in the form of a URL that is only accessible for this session. You can do this using the URL.createObjectURL(File_orBlob) method.
  • To save this image on your server. Avoid storing a ~37% larger base64 encoded version, and instead send and store the file directly as a file (multipart). This can be easily accomplished with the FormData API.

inp.onchange = function(){
  var file = this.files[0];
  if(file.type.indexOf('image/') !== 0){
    console.warn('not an image');
    }
  var img = new Image();
  img.src = URL.createObjectURL(file);
  
  img.onload = function(){
    URL.revokeObjectURL(this.src);
    };
  document.body.appendChild(img);
  }

function sendToServer(){
  var file = inp.files[0];
  var form = new FormData();

  form.append('image', file); 
  form.append('otherInfo', 'some other infos');
  var xhr = new XMLHttpRequest();
  xhr.open('post', 'yourServer/uploadPage')
  xhr.onload = function(){
    console.log('saved');
    };
  xhr.send(form);
  }
<input type="file" id="inp">

And if PHP code is needed to extract the File from this request:

if ( isset( $_FILES["image"] ) ){
  $dir = 'some/dir/';
  $blob = file_get_contents($_FILES["image"]['tmp_name']);
  file_put_contents($dir.$_FILES["image"]["name"], $blob);
}

Answer №2

To securely save and access files, you should first upload them to a server that hosts your backend processes. From there, take the following steps:

  1. Verify the file for security purposes
  2. Save the file on either a physical server or cloud storage platform
  3. Create an entry in a database linking the file's path or ID to the user who uploaded it (this enables easy retrieval when necessary)

In essence, rather than storing the actual image in the database, store it on a file sharing service or cloud provider and keep only essential information required for downloading/retrieving the image later on.

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

Unlocking the AngularJS variable within the template script

My controller code: $scope.totals = totals; In the template, I am able to successfully inject HTML using this code: {{totals}} However, my goal is to access the totals variable in a script within the template. Here's what I attempted: <script& ...

What could be causing my jQuery getJSON function to not execute the callback function as expected?

I'm facing an issue with my JavaScript code: $(document).ready(function(){ $("#EstadoId").change(function(){ listaCidade($(this).val()); }); }); function listaCidade(uf) { $.getJSON("@Url.Action("ListaCida ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

Alternative for document.ready in AngularJS when outside of AngularJS

I am currently developing a small Chrome extension that will interact with an Angular website. I have managed to successfully detect full page reloads using $(document).ready(), but I am facing issues when it comes to detecting page changes triggered by ng ...

What is the best way to center align my horizontal subnav?

I am currently working on a horizontal navbar with horizontal submenus. One issue I am facing is getting the elements in mysubnav to align centrally instead of being pushed to the left all the time. If you need a visual representation of what I mean, plea ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

What is the correct way to type this?

Looking for some help with my React Component: const CustomIcon = ({ icon, ...props }: { icon: keyof IconType }) => { const Icon = Icons[icon] return <Icon {...props} /> } I'm attempting to use it like this: <CustomIcon icon={normalTe ...

Tips for coordinating web service requests in JavaScript

My control application utilizes asp.net webservices for functionality. A timer is set to perform an asynchronous webservice call every 5 seconds in order to update the screen. Additionally, there are user buttons that trigger parts of the screen to refres ...

A guide to performing a LEFT JOIN on two JSON data sources from external URLs

I've been attempting to achieve the following outcome using external JSON data but haven't had any luck finding a solution on search engines or forums. Can anyone provide assistance with this? Thank you in advance. people = [{id: 1, name: "Tom" ...

The ReCaptcha and AJAX Integration

I am attempting to display the ReCaptcha image using its AJAX API. I have been following the instructions from this documentation and observing the behavior of this demo. Despite my efforts, I am still unable to create a functional fiddle. I have added jsf ...

Exploring Selenium: Clicking on Auto-Complete Suggestions using Python

Attempting to interact with an auto-complete search bar on the site in order to search for results. Wanting to click on the drop-down element that appears after entering a city name to perform a full city name search and obtain results. Below is the cod ...

D3.js Issue: The <g> element's transform attribute is expecting a number, but instead received "translate(NaN,NaN)"

I encountered an error message in my console while attempting to create a data visualization using d3. The specific error is as follows: Error: <g> attribute transform: Expected number, "translate(NaN,NaN)". To build this visualization, I ...

Is there a way to calculate the height of a component that is only rendered conditionally?

I have a scenario where I need to dynamically adjust the height of a component that is conditionally rendered without explicitly setting it. The height should automatically match the size of its content. To achieve this, I am using a reference to determin ...

Determine whether the browser is being used on an Android or iOS device

Is there a dependable method to alter buttons and text on a mobile site based on whether the user is using an Android or iOS browser? ...

Tips for displaying the Material UI Menu component on the left side instead of the default right side

Recently, I created a dropdown component using Material UI's Menu component. However, the default behavior of the menu is to open towards the right side. I actually need it to open towards the left instead. I attempted to modify its styling, and whil ...

Await the resolution of multiple individual promises

I am working with Angular promises in multiple controllers, and I need to trigger a function once all of them have completed. Is there a way to achieve this using events or promises? ...

What is the method to prevent the label from closing in the MUI 5 datepicker?

Is there a method to prevent the Material 5 Datepicker from closing when there's a label but no value? Current Scenario: Current Desired Outcome: Expected Sample Code: <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker lab ...

Does using .detach() eliminate any events?

I have a DIV that is filled with various content, and I am using the detach() and after() functions to move it around within the document. Before moving the DIV, I attach click events to the checkboxes inside it using the bind() function. Everything seems ...

I need help figuring out the proper way to establish an indexing path in cosmos db using the nodejs sdk

I'm currently facing a challenge with setting up the indexing policy for one of my cosmosdb containers. Within my cosmosdb, I have a container that stores information about user sessions. Using the node sdk, I am defining the containers, partition key ...