Naisarg Parmar
Naisarg Parmar

Reputation: 801

How to create file object of pdf from blob url (URL.createObjectURL())

I have created Object url of PDF file using url: URL.createObjectURL(file[0]).

e.g url = blob:http://0.0.0.0:5002/e468fb70-d597-4b17-bb3a-ec6272f2d7fe.

Now what I want to do is, read pdf from url=blob:http://0.0.0.0:5002/e468fb70-d597-4b17-bb3a-ec6272f2d7fe and create file object like

File(61) 
{
   name: "ICT_zbbihfc_dummy.pdf", 
   lastModified: 1548148972779, 
   lastModifiedDate: Tue Jan 22 2019 17:22:52 GMT+0800 (Singapore Standard Time), 
   webkitRelativePath: "", 
   size: 61,
   type: "application/pdf",
   webkitRelativePath: ""
}

This is in Javascript.

Upvotes: 4

Views: 5210

Answers (2)

Naisarg Parmar
Naisarg Parmar

Reputation: 801

To convert Blob object url of PDF or Image to File object

var file_object = fetch('blob:http://0.0.0.0:5002/e468fb70-d597-4b17-bb3a-ec6272f2d7fe') 
          .then(r => r.blob())
          .then(blob => {
              var file_name = Math.random().toString(36).substring(6) + '_name.pdf'; //e.g ueq6ge1j_name.pdf
              var file_object = new File([blob], file_name, {type: 'application/pdf'});
              console.log(file_object); //Output
           });
//------- 

To convert Base64 of Image to File object

var file_object = fetch('data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA') 
          .then(r => r.blob())
          .then(blob => {
              var file_name = Math.random().toString(36).substring(6) + '_name.jpeg'; //e.g ueq6ge1j_name.jpeg
              var file_object = new File([blob], file_name, {type: 'application/jpeg'});
              console.log(file_object); //Output
           });
//------- 

Upvotes: 5

T.J. Crowder
T.J. Crowder

Reputation: 1075427

In a comment you clarified:

I am selecting files from input tag. after then I am creating blob url of it. and now on submit button I want to read file from blob url as File Object..then send File Object to server.

You don't need a File object to do that. You can simply send the Blob, for instance using FormData's append method, which accepts Blobs.

However: If you have the input, and you've got the File from the input's files array, you may as well just use it directly rather than reading it and creating a Blob.

It's probably worth pointing out that input type="file" elements have a multiple attribute that can be used to specify that it can be used for multiple files (which is why the files property is a collection).

Upvotes: 1

Related Questions