Using JavaScript to convert an image URL to a File Object

Looking to obtain an image file from a URL entered into an input box, leading to the transformation of an image URL into a file object.

To illustrate, when selecting a random image on Google Images, you can either copy the Image or its URL.

In this scenario, the user copies the URL (e.g.,

https://pbs.twimg.com/profile_images/638751551457103872/KN-NzuRl.png
) and pastes it into the input box before clicking "add image." The goal is to locally access the image file via the URL so it can be passed onto ng-file-upload's function Upload.dataUrl(myImageFile) for uploading purposes.

Currently, validation checks ensure the URL is a valid image. However, the challenge lies in extracting the image itself from the provided URL.

formSubmit: function(){
      var url = document.forms["imageForm"].elements["urlImage"].value;
      console.log(url);
      if (!$scope.checkURL(url)) {
        console.log("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.")
        return(false);
      }
      $scope.testImage(url, function(testURL, result) {
        if (result == "success") {
          // you can submit the form now
          console.log("SUCCESS!");
          

        } 
        else if (result == "error") {
          console.log("The image URL does not point to an image or the correct type of image.");
        } 
        else {
          console.log("The image URL was not reachable.  Check that the URL is correct.");
        }
      });
      return(false); 

    },
    checkURL: function(url){
      return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
    },
    testImage: function(url, callback, timeout) {
      timeout = timeout || 5000;
      var timedOut = false, timer;
      var img = new Image();
      img.onerror = img.onabort = function() {
          if (!timedOut) {
              clearTimeout(timer);
              callback(url, "error");
          }
      };
      img.onload = function() {
          if (!timedOut) {
              clearTimeout(timer);
              callback(url, "success");
          }
      };
      img.src = url;
      timer = setTimeout(function() {
          timedOut = true;
          callback(url, "timeout");
      }, timeout); 
    }

Your help in resolving this issue would be highly appreciated!

Answer №1

No need to make it complicated
It can be easily done

document.getElementById("photo").src = document.forms["myForm"]["userInput"].value;

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

Tips for implementing PHP Instagram Signature using AJAX

I'm facing a challenge with the latest Instagram API, which now requires an Enforced Signed request that includes both an Access Token and Client Secret to generate a Signature. If anyone could spare some time to help me out, I would greatly apprecia ...

Whenever I use Vue JS, I notice that it displays [Object object] on console.log and returns Undefined when

Currently, I'm developing Vue.JS code to showcase data fetched by PHP from a server. The PHP sends a JSON object to the Vue for display. Below is my existing code snippet: axiosPost(); } function axiosPost() { axios.post( './Conver ...

Warning: React detects a missing dependency within an interval in the effect

A webpage I developed using React and Next.js has the following structure. import Head from 'next/head'; import { useEffect, useState } from 'react'; import Header from '../components/Header'; export default function Home() { ...

Partial postback in ASP.net Ajax and JQuery: enhancing user experience

There is a radiobutton list and a repeater inside an updatepanel. The repeater is utilizing a jQuery tools plugin known as scrollable. Although the scrollable plugin functions properly after the initial page load, it stops working when a radio button is c ...

Using jQuery to create dynamic elements that fade out with timers

My website has a simple message system that displays messages in a floating div at the top of the page. Each message is supposed to fade out after a certain amount of time, but I want users to be able to pause the fading process by hovering over the messag ...

Tips for changing a entry with Ajax on WordPress

I apologize if this question has already been addressed. I am new to Ajax and currently attempting to modify a record within the users table of WordPress. Utilizing a for loop to display users, the query is as follows: foreach($user_info as $newu){ ?> ...

Looking for a specific text on $location update in AngularJS

Is there a way in AngularJS to search the DOM for text after a new view is loaded? The filter almost does this, but I'm not interested in returning a new array of elements. For instance; html <div ng-view=""> <ul> &l ...

"Utilize Angular's $http options for requesting instead of using

When I attempt to send a $http POST request to a server API, the request method unexpectedly changes to OPTIONS. Strangely, this issue only occurs when working with localhost. To troubleshoot, I tried making the same request using Postman and it worked fla ...

AJAX request made to a specific local directory, instead of the usual localhost

Currently, I am working on a project to create a database that can be filtered using various options. My approach was to keep it simple by using HTML for sliders and checkboxes, along with JavaScript/jQuery for filtering the results. This setup allows me t ...

Having difficulty submitting a form with ajax, while accomplishing the same task effortlessly without ajax

I have been experimenting with submitting a form using ajax to the same .php file. When I submit the form without ajax directly (form action), the database gets updated. However, when I try the same process with ajax, there is no change in the database. H ...

Numerous routers available for enhancing functionality in an Ember application

Can an Ember app have multiple router.js files? By default, one router.js file will look like this: import Ember from 'ember'; import config from '../../config/environment'; var Router = Ember.Router.extend({ location: config.locat ...

The tooltip callback in react-chartjs-2 is failing to function as expected

I've been utilizing the react-chartjs-2 library to create basic charts in my React project. In an attempt to customize the tooltip, I added a title: tooltips: { callbacks: { label: (tooltipItem, data) => { return tooltipItem?.valu ...

Set up an event listener for a specific class within the cells of a table

After spending the last couple of days immersed in various web development resources, I find myself stuck on a particular issue. As someone new to this field, the learning curve is quite steep... Let's take a look at a single row in my project: < ...

Ensure the computed variable is always up-to-date using Firebase in VueJS

After a successful sign-in through Firebase authentication, I need to update a navigation link. The user login changes are managed within the created hook using .onAuthStateChanged() data () { return { user: null, additionaluserinfo: nul ...

Encountering an undefined property error while trying to access index '0' in Angular 6 with Angular Material's mat-radio-group component, specifically when attempting to set a dynamic variable within

Currently, I am working with Angular 6 and Angular Material. My project involves a dynamic list of polls with various options. I am attempting to display the selected option using two-way data binding. However, due to the dynamic nature of my list, I have ...

Trigger a re-render in React using setState(null) and forceUpdate()

When using react 16, setState(null) no longer triggers an update according to the official documentation: The new behavior for calling setState with null is that it does not trigger an update. This gives you the control in the updater function to decide ...

Reviewing and Implementing React and Material-UI Autocomplete for Selecting Multiple

Having trouble using Formik and MUI Autocomplete with multiple items. Specifically, when searching for "Pencil", it doesn't highlight the item. Also, you can select it twice by clicking on it. Desired outcome: Being able to select one or more items. ...

Flask causing AJAX Request to encounter a CORS Policy issue

Currently, I am utilizing Flask to construct a basic backoffice system. In an attempt to execute some requests on the client-side using AJAX, I keep encountering a persistent error: Access to XMLHttpRequest at '...' from origin 'http://lo ...

Automatically closing the AppDateTimePicker modal in Vuexy theme after selecting a date

I am currently developing a Vue.js application using the Vuexy theme. One issue I have encountered is with a datetimepicker within a modal. The problem arises when I try to select a date on the datetimepicker component - it closes the modal instead of stay ...

What is the best method for styling arrays displayed by React in version 15 using CSS?

React v15 has made a change where elements of arrays in JSX are now rendered as <!--react-text:some_id-->text<!--/react-text--> instead of spans. I've searched for a solution but haven't been able to figure out how to apply CSS styles ...