I want to read the file in the form of blob.

Asked 2 years ago, Updated 2 years ago, 17 views

I'm a beginner at javascript, but
We create a web application by combining sample codes.
I have a question about loading files.

In html

<input type="file" class="input_02_file" multiple/>

and in .js

var B=doc.querySelector(".input_02_file").files

Then the blob file list will be in B.

However, it is troublesome to specify a file every time.
So I thought I could put the file in the same directory as the script and load it.
My hope is that B will be loaded automatically. Is it possible?

I looked into various things, but I didn't understand, so I asked you a question.
I would appreciate it if you could give me a hint.Thank you for your cooperation.

Add

Thank you for your comment.The app is an image that reads several images with readAsDataURL() and switches them with a slider.
I would like to load the image sample in the initial state.
If I could create a blob type or file instance from the absolute path (".images/sample.png"), I could read the image using the function above.

https://stackoverflow.com/questions/25046301/convert-url-to-file-or-blob-for-filereader-readasdataurl
I'm reading it for your reference.

javascript

2022-09-29 21:48

1 Answers

You want to read the sample data prepared on the server side as Blob.

In XMLHttpRequest, xhr.responseType can be specified as blob to retrieve the response as Blob.

This is the minimum code that eliminates error handling.

var req = new XMLHttpRequest();
req.open("GET", "https://i.imgur.com/rjI42fW.png", true);
req.responseType="blob";

req.onload=function(e){
  // e.target or req
  var blob = e.target.response;
  document.write('<img src='+window.URL.createObjectURL(blob)+'>');
};

req.send();

I think it will be fine this time, but since it is XHR, it is subject to CORS restrictions.If the resource is in a different origin, print the appropriate header.

Reference


2022-09-29 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.