


How to upload pictures asynchronously using Ajax (html, javascript, php)_PHP tutorial
How to upload images asynchronously using Ajax (html, javascript, php)
In the first two days of the project, I needed to use the functions of asynchronously uploading pictures and displaying the upload progress, so I found a lot of foreign articles and encountered various pitfalls over the mountains and ridges. I wrote an article to record them here.
HTML
There is nothing much to say about the HTML code, just a form and input of file type. Let's look at the js part.
javascript
<code class="javascript" hljs=""> //绑定了`submit`事件。 $('#fileupload-form').on('submit',(function(e) { e.preventDefault(); //序列化表单 var serializeData = $(this).serialize(); // var formData = new FormData(this); $(this).ajaxSubmit({ type:'POST', url: *yoururl*, dataType: 'json', data: serializeData, // data: formData, //attention!!! contentType: false, cache: false, processData:false, beforeSubmit: function() { //上传图片之前的处理 }, uploadProgress: function (event, position, total, percentComplete){ //在这里控制进度条 }, success:function(){ }, error:function(data){ alert('上传图片出错'); } }); })); //绑定文件选择事件,一选择了图片,就让`form`提交。 $(#fileupload).on(change, function() { $(this).parent().submit(); });</code>
PHP
<code class="php" hljs=""><!--?php //通过$_FILES[]去获取文件 echo '$_FILES['file']';</code--></code>
遇到的坑:
Its value can be obtained through methods such as 序列化表单,因为是文件,不能通过<code>val()
and text()
, which can only be submitted through a serialized form. .serialize()
is used in the code. Another way is to use .FormData()
to submit. However, during the experiment, it worked normally at first, but later an error was reported. On stackoverflow.com, someone saw that someone had encountered the same problem and had no solution, so they gave up. For ordinary ajax
, it is impossible or difficult to get the upload progress. A plug-in, jQuery Form Plugin, is used here. The method of use is very simple. The original configuration of ajax
can be used, and it has many practical functions and detailed usage documents. Recommended ~ ajax
These three parameters for uploading images must be configured contentType: false, cache: false, processData:false,
. Get a local preview, this method may have browser compatibility issues.
<code class="php" hljs=""><code class="javascript" hljs="">$(#fileupload).change(function(){ if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#theImg').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); } }</code></code>
Note in the php part that although Ajax uses the <code>POST<code class="php" hljs="">php部分注意虽然Ajax那里使用的是<code>POST
method, when accepting files in the background, $_FILES<code>$_FILES
. You can use $_FILES['file']['type']<code>$_FILES['file']['type']
to determine the file format for safe processing. We are just demonstrating here. There are other parameters, such as tmp_name<code>tmp_name
is the file path, and name<code>name
is the file name. After receiving in the background, you can use move_uploaded_file()<code>move_uploaded_file()
to save the file to the server. Not much to say here.
Other supplements<code class="php" hljs="">其他补充
In addition, @_w student added that you can also point to a current page by setting the <code>target<code class="php" hljs="">另外@_w同学补充,不刷新页面还可以通过设置<code>form
attribute of form<code>target
without refreshing the page. Hidden iframe<code>iframe
to achieve. Let that iframe<code>iframe
refresh the jump page. The jQuery Form Plugin mentioned above also allows you to do this.
In addition, I recommend a plug-in jquery-iframe-transport
Recommended reading<code class="php" hljs="">推荐阅读
uploading-files-with-ajax image-upload-example jquery-progress-bar-for-php-ajax-file-upload <code class="php" hljs="">uploading-files-with-ajax image-upload-example jquery-progress-bar-for-php-ajax-file-upload
<code>javascript<code class="php" hljs=""><code>javascript
I am a newbie, I hope this article can help more people who encounter the same problem. If something is written poorly or incorrectly, I hope colleagues can kindly point it out.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the "My" button in the lower right corner; (2) On the personal center page, find "Settings" and click it; (3) Scroll down and find the "Clear Cache" option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

With the popularity of Douyin short videos, user interactions in the comment area have become more colorful. Some users wish to share images in comments to better express their opinions or emotions. So, how to post pictures in TikTok comments? This article will answer this question in detail and provide you with some related tips and precautions. 1. How to post pictures in Douyin comments? 1. Open Douyin: First, you need to open Douyin APP and log in to your account. 2. Find the comment area: When browsing or posting a short video, find the place where you want to comment and click the "Comment" button. 3. Enter your comment content: Enter your comment content in the comment area. 4. Choose to send a picture: In the interface for entering comment content, you will see a "picture" button or a "+" button, click

In PowerPoint, it is a common technique to display pictures one by one, which can be achieved by setting animation effects. This guide details the steps to implement this technique, including basic setup, image insertion, adding animation, and adjusting animation order and timing. Additionally, advanced settings and adjustments are provided, such as using triggers, adjusting animation speed and order, and previewing animation effects. By following these steps and tips, users can easily set up pictures to appear one after another in PowerPoint, thereby enhancing the visual impact of the presentation and grabbing the attention of the audience.

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

When using WPS office software, we found that not only one form is used, tables and pictures can be added to the text, pictures can also be added to the table, etc. These are all used together to make the content of the entire document look richer. , if you need to insert two pictures into the document and they need to be arranged side by side. Our next course can solve this problem: how to place two pictures side by side in a wps document. 1. First, you need to open the WPS software and find the picture you want to adjust. Left-click the picture and a menu bar will pop up, select "Page Layout". 2. Select "Tight wrapping" in text wrapping. 3. After all the pictures you need are confirmed to be set to "Tight text wrapping", you can drag the pictures to the appropriate position and click on the first picture.
