总结:ajax上传图片有几种方式 -php+ajax上传文件

第一种:直接利用jquery $.ajax上传

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>

</head>
<body>

<form  enctype="multipart/form-data">	
<input type="file" name="myfile" id="fileid">

//第三种方法使用按钮
<input type="button" value="tijiao" id="filesubmit">

</form>
<script src="/static/jquery.2.1.1.min.js"></script>
<script src="/static/ajax_file_upload.js"></script>	
<script src="https://cdn.bootcss.com/jquery.form/4.2.2/jquery.form.js
"></script>	
<script>
$("#fileid").change(function(){
filedata=new FormData();//必须
filedata.append('filearr',$("#fileid")[0].files[0]);//必须
$.ajax({
            url: "{:url('uploads')}", //用于文件上传的服务器端请求地址
            dataType: 'json', //返回值类型 一般设置为json
            type: 'post',
            data:filedata,
            async:false,//必须
            contentType:false,//必须
            processData:false,//必须
            //cache:false,
           
            success: function (data, status)  //服务器成功响应处理函数
            {
                console.log(data)
               // return;
                // if (typeof (data.error) != 'undefined') {
                //     if (data.error != '') {
                //         alert(data.error);
                //     } else {
                //         alert(data.msg);
                //     }
                // }
            },
            error: function (data, status, e)//服务器响应失败处理函数
            {
                alert(e);
            }
        }
    );
    return false;
})


</script>	

</body>
</html>

//说明php后端接受的数据$_FILES['filearr']

第二种:利用 ajax_file_upload  $.ajaxFileUpload上传

<script>
$("#fileid").change(function(){
$.ajaxFileUpload({
            url: "{:url('uploads')}", //用于文件上传的服务器端请求地址
            secureuri: false, //是否需要安全协议,一般设置为false
            fileElementId: 'fileid', //文件上传域的ID
            dataType: 'json', //返回值类型 一般设置为json
            type: 'post',
            success: function (data, status)  //服务器成功响应处理函数
            {
                console.log(data)
                return;
                // if (typeof (data.error) != 'undefined') {
                //     if (data.error != '') {
                //         alert(data.error);
                //     } else {
                //         alert(data.msg);
                //     }
                // }
            },
            error: function (data, status, e)//服务器响应失败处理函数
            {
                alert(e);
            }
        }
    );
    return false;
})


</script>	

 第三种:利用jquery.form.js  ajaxForm或ajaxSubmit上传

<script>

$(function(){

var abc={
//url:"{:url('upl')}",      //form提交数据的地址
type:'post',     //form提交的方式(method:post/get)
beforeSerialize:function(){}, //序列化提交数据之前的回调函数
beforeSubmit:function(){},  //提交前执行的回调函数
success:function(data){ console.log(data)}
};

 //第一种提交方式:
 $("form").ajaxform(abc);按钮type必须submit



//第二种提交方式:
 $("#filesubmit").click(function(){//按钮type,button或submit都可
 	 $("form").ajaxSubmit(abc);
 	 return false;
 })


/*ajaxForm执行的时候其实相当于

 $("form").submit(function(){
            $(this).ajaxSubmit();
            return false;        //此句解释了为什么ajaxForm会自动提交表单,想要阻止自动提交,必须return false;
        })*/


})
</script>

其实还有多种方式,在这里就介绍三种常用的ajax上传方法,后端上传方法就不在此说明了,童鞋们,可以自己逐一试试呢!

希望对你的学习有帮助! 

 

<div class="post-text" itemprop="text"> <p>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 </p> <p>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 <a href="https://stackoverflow.com/questions/35940290/how-to-convert-base64-string-to-javascript-file-object-like-as-from-file-input-f?noredirect=1&lq=1">How to convert Base64 String to javascript file object like as from file input form?</a> 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. </p> <p>This is my code that I been working on.</p> <p><strong>index.php</strong></p> <pre><code><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> </code></pre> <p><strong>x.php</strong></p> <pre><code><?php $file=$_FILES['blob_url']['name']; $location='images/'.$file; move_uploaded_file($_FILES['blob_url']['tmp_name'],$location); ?> </code></pre> <p>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.</p> </div>
<div class="post-text" itemprop="text"> <p>I want to send the image data from the html img tag using AJAX and save it in my MySQL db. I have a column in my db which is a longblob datatype, thats where I'm going to store the image. I also have other data that I'm going to save along with it but my main concern is the image, I don't know how to do it. I did try to find answers here on and other sites but didn't find what I was looking for. My code looks like this.</p> <p>HTML:</p> <pre><code><div class="col-lg-12"> <div class="form-group col-lg-4"> <label>ARP No.</label> <label> <input type="text" name="arp-no" class="form-control" id='arp-no' required=""/> </label> </div> <div class="form-group col-lg-4"> <label>Owner</label> <label> <input type="text" name="owner" id="owner" class="form-control" value="" required=""/> </label> </div> </div> </code></pre> <p>this is where the image tag is</p> <pre><code><div class="col-lg-6"> <div class="form-group col-lg-12"> <img name="map-sketch" id="image" width="100%" height="100%" src='http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg'></img> </div> </div> <div class="row"> <div class="col-lg-1"> <button type="button" class="btn btn-primary" onclick="saveFaas()">Save</button> </div> <div class="col-lg-2" id="saving-info"></div> </div> </code></pre> <p>Javascript AJAX:</p> <pre><code>function saveFaas(){ if (confirm('Are you sure you want to save this information?')) { var params = 'kind=land'; params += '&arp-no='+document.getElementById('arp-no').value; params += '&owner='+document.getElementById('owner').value; //the image data params += '&image='; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("saving-info").innerHTML = xmlhttp.responseText; }else { // waiting for result document.getElementById('saving-info').innerHTML = '<img src="../images/ajax_loader.gif">'; } } xmlhttp.open("POST", "../functions/save-faas.php", true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp.send(params); }} </code></pre> <p>Can I pass the image data like the others?</p> <p>Php:</p> <pre><code><?php //db info include('../fragments/db-config.php'); // Create connection $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $kind = $_POST['kind']; if ($kind == 'land') { $image = $_POST['image']; // the image $arp_no = $_POST['arp-no']; $owner = $_POST['owner']; $sql = "UPDATE faas SET arp_number='$arp_no', owner_name='$owner' WHERE faas_id=$faas_id;"; } if ($conn->query($sql) === TRUE) { echo "<label>Record Updated</label>"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?> </code></pre> <p>So to wrap it up. I have an image data in my html, call ajax to send the image and the other data in php and save it in mysql db.</p> <p>My javascript code here is in plain javascript so I would like a plain javascript solution also. Thank you.</p> </div>
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页