The process of accessing a file object by using the file path given

Is there a way to retrieve the file object of an image that is stored in my website's folder without using "input type = "file"? The image is already saved on the website. Here is what I have tried so far:

var file = new File([""], "../writeto/image.png", {
    type: "png",
})

console.log(file);

The code above only creates an empty file object without any actual content. How can I insert the image file into the object?

Answer №1

Creating a "file" directly from a URL is not possible. However, you can achieve this by requesting the file via XHR (XMLHttpRequest).

Below is a useful function that is neatly packaged for easy reuse. Feel free to customize it according to your needs, such as accepting different filenames and file types.

function getFileFromUrl(url){
  let response = await fetch(url);
  let data = await response.blob();
  let metadata = {
    type: "image/png"
  };
  return new File([data], "output.png", metadata);
}
const file = getFileFromUrl("url/picture.png");

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

My goal is to retrieve and print the duplicated values only once from an associative array

Given an associative array, I need to print all the department names without any repetitions. <h3>2. List out all department names</h3> <div class="all"> </div> Here is my JavaScript code: var employee=[{"firstName":"Zahir","last ...

How to insert an array into another array in JavaScript

Using Node, express, and mongoose to work on a project. I am attempting to include an Array as an element within another Array through a callback function. app.get('/view', function(req, res){ var csvRows = []; Invitation.find({}, func ...

Highcharts: Show tooltip above all elements

Is there a way to configure tooltip display above all elements? I want to define specific coordinates so that the tooltip remains open even if it is covering the chart, and only closes when interacting with the top block. Screenshot 1 Screenshot 2 For e ...

Error 422 encountered while trying to create a new asset using the Contentful Content Management API

My attempt to create and publish an image as an asset using the Contentful Content Management API has hit a roadblock. I managed to successfully create and publish an entry, but I can't seem to figure out why creating an asset is not working as expect ...

Incorporate image into Vue.js form along with other information

I have been successfully sending the content of multiple fields in a form to the Database. Now I am looking to add an additional field for uploading images/files and including it with the other form fields, but I am unsure about how to accomplish this task ...

Having trouble toggling between the trending and search features on giphy website

I've been developing a chat application with NextJS and I'm currently working on integrating GIPHY images into it. Although I have the basic setup in place, I'm facing issues when switching between the giphy.search() and giphy.trending() fu ...

Encountering a tIDENTIFIER syntax error while trying to include a button_tag in Rails

Currently, I am in the process of developing a rails application and my aim is to incorporate a button that executes a javascript onclick function. The code snippet I am using for this purpose is: <%= button_tag "Action" type: "button", onclick: "test( ...

When resetting the function, make sure to move the class to the closest sibling element

I am currently utilizing a slider that employs the .prev and .next jQuery functions to toggle the active class, indicating which slide is being displayed. Here is the code responsible for this functionality. It identifies the current sibling with the acti ...

What are some ways to implement smooth scrolling when a navigation link is clicked?

I have a total of 3 links in my navigation bar and every time they are clicked, I want the page to smoothly scroll down to their designated section on the webpage. Although I have already set up the anchors, I lack experience in scripting to create the smo ...

The Ajax Auto Complete function encounters an issue when attempting to assign a value to the TextBox

I have a Textbox that utilizes an Ajax Autocomplete function. The function is functioning correctly and retrieves values from the database, populating them in the TextBox as well. However, there is a button on the page that triggers a query, fetching som ...

Attempting to upload an item using ThreeJs

Can someone assist me with loading an object file from my local browser in Threejs ( Rev 71)? I keep encountering an error that says loadModel.html:1 Uncaught SyntaxError: Unexpected token #. Even after trying to load the object file using chrome --allow- ...

Click once to change the element, but it will remain changed and will not revert back no matter how many times you

After the first click displaying "X" and then changing to "O" in my tic-tac-toe JavaScript game, subsequent clicks only show "O", failing to switch back to "X". I am currently working on creating a tic-tac-toe game using JavaScript. Upon the first click, ...

Strange alignment issues occurring solely on certain PCs

Currently, I am in the process of developing a website for a client who has requested that it be an exact replica of the mockup provided. However, I have encountered some issues with the headers and certain divs that contain background elements. Surprising ...

I need to obtain the URL pathname on a server component in Next.js version 13 - how is this achieved

I'm facing an issue with retrieving the pathname of a server component located in the app directory. Despite attempting to obtain it through window.location, I haven't been successful. Is there an alternative method I can use to achieve this? ...

Clear the page refresh value in javascript once the jquery ajax action is completed

Under specific circumstances, a jQuery ajax query is utilized to show a message on the page. By clicking "close" on the message, it will vanish. Additionally, there is JavaScript on the same page that triggers an automatic refresh every 30 seconds. My go ...

What is the reason for the malfunctioning of this button upon clicking?

Attempting to customize my personal website by making the sidebar width change when the sidebar button is clicked. I'm puzzled as to why it's not working as intended. I prefer to figure it out independently but any helpful tips would be appreciat ...

Another drop-down is hiding the bootstrap-select drop-down from view

What could be causing some parts of the first drop-down menu to be hidden by another drop-down menu below in the code snippet provided? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv= ...

"Enhancing User Interaction with jQuery Hover State Dropdown Menus

Here's my issue: I've created a drop-down menu and I want the text color to change when hovering over the menu. Additionally, I'd like the hover state to remain active when hovering over the submenu. Currently, I'm using this code: $( ...

The Vue component does not render the JS Promise and instead displays it as

After setting up a promise that will be returned once a correct event is called with the correct action, I have the following code: import {EventBus} from "./EventBus"; export function completed() { EventBus.$on('queue-action', e => { ...

Cannot save PDF files to a server using jsPDF

I'm new to this community and still learning javascript & php. I am having trouble saving my PDFs with jsPDF to the local storage on the server (automatically generated). It used to work in the past, but now when I add Canvas (javascript) to my HTML, ...