将一个blob url转换为FormData()的上传文件,并通过AJAX将其发送到PHP文件

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.

查看全部
duanmie9682
duanmie9682
2019/07/13 07:16
  • php
  • ajax
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信

2个回复