4

I want to convert a blob URL AKA (window.URL.createObjectURL(blob);) into a file object so I can use it with FormData() so I can use that as an upload image file for AJAX but I am not able to do that successfully and I can't find a way to make the blob URL into a file

object for my code situation and I know its possible to do this according to the posts I visited on here it can be done here's one of posts that claim that you can do that How to convert Base64 String to javascript file object like as from file input form? but the reason why I'm not using any of those posts methods because I don't know how to integrate their methods to my code situation or its too complicated to understand.

This is my code that I been working on.

index.php

<script>

document.addEventListener('DOMContentLoaded',function(){

document.querySelector('#image-input').addEventListener('change',createABlobUrlForAImgSrcAndUseThatAsAFileUploadFile);

function createABlobUrlForAImgSrcAndUseThatAsAFileUploadFile(){

//Creating a blob URL

var image_input = document.querySelector('#image-input').files[0];

var file_type= image_input.type;

var blob = new Blob([image_input], { type: file_type || 'application/*'});

var blob_url= window.URL.createObjectURL(blob); //<-Example blob:http://localhost/ed6761d2-2bb4-4f97-a6d8-a35c84621ba5

//

//Form data
var formData= new FormData();

formData.append('blob_url', blob_url);
//

//<AJAX>
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function(){

if(xhr.readyState == 4){

document.querySelector('#output').innerHTML= xhr.responseText;

//<Allow JS in AJAX request>
var exJS= document.querySelectorAll('#output script');
var enableAll= exJS.length;
for(var i=0; i < enableAll.length; i++){
eval(exJS[i].text);
}
//</Allow JS in AJAX request>

}
}

xhr.open('POST','x');
xhr.send(formData);
//</AJAX>
}

});

</script>

<input id='image-input' type='file'>

<div id='output'></div>

x.php

<?php

$file=$_FILES['blob_url']['name'];
$location='images/'.$file;
move_uploaded_file($_FILES['blob_url']['tmp_name'],$location);  

?>

I know my code is not logically correct and I will have to change my code to be able to do what I want to do so I am aware it is not logically correct. Just trying to show you guys what I mean.

1
  • @user9375528 have you got any solution? Commented May 24, 2021 at 5:03

4 Answers 4

4

This is how I got it done in my project. But in my case, I wanted to convert a blob to a wav file and then send to the back-end.

//Save your blob into a variable
var url = URL.createObjectURL(blob);

//Now convert the blob to a wav file or whatever the type you want
var wavefilefromblob = new File([blob], 'filename.wav');

//Pass the converted file to the backend/service
sendWavFiletoServer(wavefilefromblob);

//This is my function where I call the backend service to send the wav file in Form data
function sendWavFiletoServer(wavFile) {
  var formdata = new FormData();
  formdata.append("file", wavFile); 
  var ajax = new XMLHttpRequest();
  ajax.addEventListener("load", completeHandler, false);
  ajax.addEventListener("error", errorHandler, false);
  ajax.addEventListener("abort", abortHandler, false);
  ajax.open("POST", "https://yourserviceurl/api/");
  ajax.setRequestHeader('API_SECRET', UzI1NiIsInR5cCI6IkpXVCJ9eyLCJleHAiO');
  ajax.send(formdata); 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for you reply and example I don't think your understanding what I want to do exactly I basically plan to use the blob urls in p tags for example like this <p id='a1'>blob:localhost/ed6761d2-2bb4-4f97-a6d8-a35c84621ba5</p> and then get that blob urls from the p tag and covert it to a upload because I know a blob url is not a blob it's just a reference to a blob I just want to use the blob url that reference to a blob as a file input file I hope you know what I mean now . Use blob urls and get which blob url belong to what blob and convert it to a file input
document.querySelector('#a1).innerHTML; and convert the blob url to make a reference to its blob and convert it to a file upload
3

I had the same question and found a way.

This will give you a Blob object:

let blob = await fetch(url).then(r => r.blob());

1 Comment

While this is probably slower / less-efficient than the examples where you are handling the blob in one code block, this works for me in my stack using React / Redux where I may have a component that handles picking the image and, another component further up the tree that handles uploading the image - Redux complains about File objects being non-serializable
1

I think uploading form data should be a blob object, not a blob URL

javascrip:

var image_input = document.querySelector('#image-input').files[0];
var blob_url= window.URL.createObjectURL(image_input); 
//Form data
var formData= new FormData();
// ...

// here , content-type: multipart/form-data
formData.append('upload_file', image_input);

php:

$file=$_FILES['upload_file']['name'];
$location='images/'.$file;
move_uploaded_file($_FILES['upload_file']['tmp_name'],$location);  

1 Comment

Thanks for your feed back i'm not asking to send a blob url I basically want to convert the blob url on the client side into a file because I know that a blob url is just a reference to a blob because I plan to have blob urls on the page and then I want to get them like this for example <p id='a1'>blob:localhost/ed6761d2-2bb4-4f97-a6d8-a35c84621ba5</p> and then use JS like this document.querySelector('#a1').innerHTML; and then convert it to a file upload because I know a blob url is just a reference to a blob I hope you understand what i'm trying to do.
0

I use below code and it worked for me

var fileFromBlob = new File([videoFile], 'uidVideo.mp4');

// Create new form data
const form = new FormData();
form.append('file', fileFromBlob);
    

//custom function for call api
const { statusCode } = await apiCallFn('POST', form, routes.uidVideo, false, true);
console.log(statusCode);
    
    
/////////////////////// api call function that come in the top code
export const apiCallFn = async (method, data, url, agent, type) => {
  const accessToken = localStorage.getItem('token');
  // build config
  let config = {
    method,
    url,
    data,
    headers: {
      'Content-Type': type ? 'multipart/form-data' : 'application/json',
      Authorization: 'Bearer' + ' ' + accessToken,
      accept: 'application/json',
    },
  };

  if (agent) {
    config['headers']['agent'] = agent;
  }

  // Call axios function to get or post data
  try {
    const { data } = await axios(config);
    // console.log("data", response.data);
    return Promise.resolve(data);
  } catch (error) {
    // const { statusCode } = error.response.data;
    // console.log(error.response.data);
    console.log(error.response.data);
    return Promise.resolve(error.response.data);
  }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.