jQuery+PHP base64图片上传
作者:互联网
1.把base64编码的图片转换为Blob对象
//base64编码转为Blob对象 dataURLtoFile = function(dataurl, filename) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } var theBlob = new Blob([u8arr], {type: mime }); theBlob.lastModifiedDate =new Date(); theBlob.name = filename; return theBlob; }
2.用ajax上传图片
var form = new FormData(); $('.list img').each(function(){ var filename = $(this).attr("alt"); if(filename != "copy"){ form.append('images[]',dataURLtoFile($(this).attr("src"), filename),filename); } }); $.ajax({ url: 'url', async: true, type: 'post', data: form, processData: false, contentType: false, success: function(data){ //TODO } });
3.PHP对请求进行处理
public function uploadImages(){ if(isset($_FILES["images"])){ $tmp_name = $_FILES["images"]["tmp_name"]; $name = $_FILES["images"]["name"]; for($i = 0;$i < count($tmp_name);$i++){ $fileinfo = pathinfo($name[$i]); //文件后缀名 $fileext = strtolower($fileinfo["extension"]); if ( $fileext != 'png' && $fileext != 'jpg' && $fileext != 'gif' && $fileext != 'jpeg' ){ continue; } if (!file_exists(IMAGE_TEMP_PATH)){ mkdir(IMAGE_TEMP_PATH, 0777, true); } move_uploaded_file($tmp_name[$i], IMAGE_TEMP_PATH.$name[$i]); echo $_FILES["images"]["error"][$i]; } } }
标签:jQuery,tmp,name,base64,filename,fileext,images,new,PHP 来源: https://www.cnblogs.com/diehuacanmeng/p/13402784.html