-4

Is it possible to use hardcoded filename?

I want to read File of an image.

I have hardcoded filename like, '/Users/Desktop/1.jpg' and i want to use this as a file.

I want to change this '/Users/Desktop/1.jpg' type as file.

var imageURL = '/Users/Desktop/1.jpg';

new File(imageURL);

alert(typeof(imageURL));  // I want this as a File
Charu
  • 23
  • 7
  • 2
    Can you include further details of what you are trying to accomplish at Question? – guest271314 Aug 05 '17 at 05:56
  • I just use this in extend javascript, var img=new File('1.jpg''); Its create a file. but i want to use this in javascript / jquery – Charu Aug 05 '17 at 06:21

1 Answers1

0

The simplest approach would be to click or drag and drop the file at an <input type="file"> element.

<input type="file" accept="image/*">
<script>
  const input = document.querySelector("input");
  input.onchange = function(event) {
    const file = event.target.files[0];
    console.log(file);
  }
</script>

If the file is served with CORS headers you can request the file using Image constructor and pass the <img> reference to canvas.toBlob(), then pass Blob reference to File constructor, optionally set the name of the File object.

Similarly CORS headers are necessary when using fetch() and Response.blob() to get Blob of image.

Note if using Chrome or Chromium browser to request files at local filesystem you can launch Chrome or Chromium browsers with --allow-file-access-from-files flag to access local filesystem at JavaScript and HTML, see Read local XML with JS.

guest271314
  • 1
  • 15
  • 104
  • 177
  • But i want to use the local file dynamically. In this approach, file is selected by user.I have ask its alternate solution. pls refer how to set a value on input type file dynamically. – Charu Aug 05 '17 at 07:51
  • It is only possible to set the `.files` property to a `FileList` object, for example, using drag and drop. Else use `new Image()` or `fetch()` to request the file – guest271314 Aug 05 '17 at 07:56