我想将 blob URL AKA (window.URL.createObjectURL(blob);) 转换为文件对象,以便可以将其与 FormData() 一起使用,这样我就可以将其用作 AJAX 的上传图像文件,但我不能成功执行此操作,但我找不到将 blob URL 放入文件的方法
我的代码情况的对象,我知道根据我在这里访问的帖子可以做到这一点,这是声称你可以做到的帖子之一 How to convert Base64 String to javascript file object like as from file input form?但是我不使用任何这些帖子方法的原因是因为我不知道如何将它们的方法集成到我的代码情况中,或者它太复杂而难以理解。
这是我一直在处理的代码。
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);
?>
我知道我的代码在逻辑上不正确,我将不得不更改我的代码才能做我想做的事情,所以我知道它在逻辑上不正确。只是想向你们展示我的意思。
最佳答案
这就是我在项目中完成它的方式。但就我而言,我想将 blob 转换为 wav 文件,然后发送到后端。
//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);
}
关于javascript - 将 blob url 转换为 FormData() 的上传文件并通过 AJAX 将其发送到 PHP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57016985/