How to upload files and images asynchronously with ajax
This time I will show you how ajax can upload files and pictures asynchronously. What are the precautions for ajax to upload files and pictures asynchronously. Here is a practical case, let’s take a look.
Hello everyone, in this article I want to share with you the code for the file upload function of a webpage. I hope you can have some reference or give me some suggestions.
As we all know, most major websites nowadays basically have a file upload function. Users can save their favorite pictures or other files online so that they can be easily found when they are used in the future. But the files of a web page How to set up the upload function? Today I will take image upload as an example to show you the specific steps of the file upload function.
In fact, there are two ways to upload files, one is from form submit submission, and the other is asynchronous submission through ajax. However, a problem with form form submission is that the interface will be refreshed every time the upload is completed, which cannot be implemented. Asynchronous upload, so now almost all websites use ajax asynchronous upload. Now I will show you how to implement ajax asynchronous upload.
First I create a form form, the code is as follows:
After the creation is completed, first we need to get the information of the image uploaded by the user from this book, the code is as follows
var imgs=[];//存储图片链接 //为文件上传添加change事件 var fileM=document.querySelector("#file"); $("#file").on("change",function(){ console.log(fileM.files); //获取文件对象,files是文件选取控件的属性,存储的是文件选取控件选取的文件对象,类型是一个数组 var fileObj=fileM.files[0]; //创建formdata对象,formData用来存储表单的数据,表单数据时以键值对形式存储的。 var formData=new FormData(); formData.append('file',fileObj);
The formData here is the object we want to store file information now, and then we need to submit it to the backend using an ajax request:
//创建ajax对象 var ajax=new XMLHttpRequest(); //发送POST请求 ajax.open("POST","http://localhost/phpClass/file-upload/move_file.php",true); ajax.send(formData); ajax.onreadystatechange=function(){ if (ajax.readyState == 4) { if (ajax.status>=200 &&ajax.status"); $(".con").append(img); imgs.push(obj.msg); }else{ alert(obj.msg); } } } } });
Then after our request is successful, the backend must handle it accordingly. And save the pictures to the specified folder, so the corresponding PHP should complete these operations:
<?php //解决跨域问题 header("Access-Control-Allow-Origin:*"); //说明向前台返回的数据类型为JSON header("Content-type:text/json"); //$_FILES超全局变量存储是文件数据,是一个关联数组 $fileObj=$_FILES['file']; var_dump($fileObj); if($fileObj["error"]==0){ //判断文件是否合法 $types=["jpg","jpeg","png","gif"]; $type = explode("/", $fileObj["type"])[1]; if(in_array($type, $types)){ $time = time();//获取时间戳 返回一个整形 //获取文件详细路径 $filePath="http://localhost/phpClass/image1".$time.".".$type; echo $filePath; //移动文件 $res=move_uploaded_file($fileObj["tmp_name"],"../image1/".$time.".".$type); if($res){ $infor=array("err"=>0,"msg"=>"文件移动成功"); }else{ $infor=array("err"=>1,"msg"=>"文件移动失败"); } }else{ $infor=array("err"=>1,"msg"=>"文件格式不合法"); } echo json_encode($infor); } ?>
In this way, we have completed all the steps of file upload. If you want to upload your favorite pictures to yourself on the web page, I hope this code can help you!
Attachment: If you need to attach other information about yourself when uploading a file, you only need to add this code after the front-end page request is completed:
//完成form表单数据的提交 $('#btn').on('click',function(){ // serializeArray()将form表单控件中的数据序列化成数组,数组中含有若干对象,对象包含对应控件的name和value var infor = $('#form').serializeArray(); // console.log(infor); var stu = {}; for (var i=0;i<infor.length><p> I believe you have read this article You have mastered the case method. For more exciting information, please pay attention to other related articles on the PHP Chinese website! </p> <p>Recommended reading: </p> <p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-394200.html" target="_blank">jQuery implements asynchronous refresh</a><br></p> <p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-394199.html" target="_blank">How jQuery issues get and post requests to the server</a><br></p></infor.length>
The above is the detailed content of How to upload files and images asynchronously with ajax. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
