Image upload and Echo Ajax asynchronous chapter
How does the image upload to the server without a refresh? After the first two articles, we come to the actual combat how to upload images asynchronously without a refresh, let's look at the effect first.
Before the actual battle, we need to do some preparatory work. For example, learn about the Formdata object
The Formdata object is used to compile data into key-value pairs so that data can be sent using XMLHttpRequest. It is primarily used to send form data, but it can also be used to send keyed data (keyed), independent of the form. If the form enctype
property is set to Multipart/form-data, the form's submit () is used for submitting the form, which is similar to the Submit Form button. ") method to send data so that the sending data has the same form. ”
This is an official explanation, and I would like to take a look at my understanding that when we new a formdata (form) object, it will help us to encapsulate the data in the form form as a key-value pair, and we used to submit the data with the submit of input, When we get this form object, we can use Ajax to simulate the submit submission of input, and now that we know this, we'll start programming it step after time.
Let's refine the interface and look at the following code
This is the contents of the body, do not forget the form, just do not have the Action,enctype property to set up, my previous article has on the enctype to explain the picture upload and echo back to the end of the article
<body><form id="formTag1" enctype="multipart/form-data"> <div class="uploadImgBtn" id="uploadImgBtn"> <input class="uploadImg" type="file" name="file" id="file1"> </div></form></body>
This is the content in CSS.
<style> .uploadImgBtn { width: 100px; height: 100px; cursor: pointer; position: relative; background: url("img/plus.png") no-repeat; -webkit-background-size: cover; background-size: cover; } .uploadImgBtn .uploadImg { position: absolute; right: 0; top: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; } .pic { width: 100px; height: 100px; } .pic img { width: 100%; height: 100%; }</style>
The basic style has been written, let's have a look.
OK, let's start writing our jquery code, before we write it, we'll figure out the idea, when the user chooses a good picture, that is, when the change event of input is triggered, we upload the image to the server, and the service returns the URL of the image, when we get the URL, Set it to the background of the box outside of our input. Now that we know the idea, we'll write the code.
<script> $(document).ready(function(){ $("#file1").on("change", upload ); }) function upload(){ /** * 我们存一下this对象, * 我们将在ajax的回调函数中, * 将要用这个对象, * 用它来改变父盒子的背景图 * */ var self = this; //如果不理解我写的,可以看看我的前几篇文章 $.ajax({ url: "/UpImg/upload", type: "post", dataType: "json", cache: false, data: new FormData($("#formTag1")[0]), processData: false,// 不处理数据 contentType: false, // 不设置内容类型 success: function(data){ /* 后端返回的数据格式为 {"url": "xxxxxx"} */ $(self).parent().css({ "background-image": "url("+data.url+")" }) } }) }</script>
We separate the execution function of the change event because we may need to use this function. The function also has no difficulty, that is, to save a This object, plus an AJAX. Let's take a look.
We have implemented the Change event trigger when we upload the image to the server, we can also alter the image we have chosen, and it is certainly not over. Because the user just chose a picture, if our business needs users to upload more than one picture, then we certainly do not meet the requirements, we need to add some functionality to our code. For example, when a user chooses one, it is regenerated into a form->input tag, and then recursively, but we also need to add some condition that we cannot generate a form->input tag when the user changes a picture that has been selected. Well, that's probably what the demand is.
Let's take a look at the idea:
1, we need to add a box outside the form tag, we put all the generated form tags inside.
2, we need to have a counter, record the number of form, also through this we can give form and input set a different ID
3, we need to determine the current change event is the first, if its ID of the value part and count, we will be reborn into a form, or return
Let's look at our HTML section first.
<body><div id="formBox"> <form id="formTag1" enctype="multipart/form-data"> <div class="uploadImgBtn" id="uploadImgBtn"> <input class="uploadImg" type="file" name="file" id="file1"> </div> </form></div></body>
Let's encode and implement JS.
<script>//As a symbol of the first few form var count = 1; $ (document). Ready (function () {$ (' #file1 '). On ("Change", upload); }); function upload () {var = this; Get It is the first few form form var num = This.getattribute ("id"). Replace (/[a-za-z]/g, ""); The selector of constructing form is var $form = "#formTag" +num; $.ajax ({url: "/upimg/upload", type: "Post", DataType: "JSON", Cache:false, Data:new FormData ($ ($form) [0]), processdata:false,//do not process data contenttype:false,//Do not set content type Success:function (data) {//Set the background for our selected picture $ (self). Parent (). css ({"B Ackground-image ":" url ("+data.url+") "}"; We regenerate into a form if (count = = num) {//count count plus 1 count +=1; var str = ' <form id= ' formtag ' +count+ ' "enctype=" multipart/form-data "> ' + ' ≪div class= "uploadimgbtn" id= "uploadimgbtn" > ' + ' <input class= "uploadimg" type= "file" Name= " File "id=" file ' +count+ ' > ' + ' </div> ' + ' </form> '; Add form $ ("#formBox") to the Outermost box. Append ($ (str)); The selector for constructing input var $sel = "#file" +count; Binds the Change event $ ($sel) for the newly generated input. On ("Change", upload); }else{//If not equal to return false; } } }); }</script>
In this way we basically achieve our effect, as in the beginning of the effect, this is unlimited to add a form, then you can set an upper bound to count, according to their own business to adjust it, to this our image upload and Echo series even if the end;
I heard that 520 is coming, we need new a talking object, 520 when we come to the actual combat new object, but also as a gift for everyone (manual funny)
Picture Upload and Echo series
How to upload multiple images with the input tag and echo
Image upload and echo back end chapter
Image upload and Echo Ajax asynchronous chapter