ajax file asynchronous implementation of form upload
This time I will bring you the asynchronous implementation of form upload with ajax file. What are the precautions for asynchronous implementation of form upload with ajax file? The following is a practical case, let’s take a look.
User uploads are always indispensable in projects. Here are the main list of form uploads and ajax uploads! Note: context.Request.Files is not suitable for operating large files. The following list is mainly for processing smallfile uploads!
Resource download: 1. jQuery official download address:https://jquery.com/download/
1. Form upload: html client part:<form action="upload.ashx" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="file1" /><br /> <input type="submit" value="上传" /> </form>
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpPostedFile file1 = context.Request.Files["file1"]; helper.uploadFile(file1, "~/upload/");//这里就是对相应方法进行调用 context.Response.Write("ok");//提示执行成功 }
/// <summary> /// 上传图片 /// </summary> /// <param name="file">通过form表达提交的文件</param> /// <param name="virpath">文件要保存的虚拟路径</param> public static void uploadImg(HttpPostedFile file,string virpath) { if (file.ContentLength > 1024 * 1024 * 4) { throw new Exception("文件不能大于4M"); } string imgtype = Path.GetExtension(file.FileName); if(imgtype!=".jpg"&&imgtype!=".jpeg") //图片类型进行限制 { throw new Exception("请上传jpg或JPEG图片"); } using (Image img = Bitmap.FromStream(file.InputStream)) { string savepath = HttpContext.Current.Server.MapPath(virpath+file.FileName); img.Save(savepath); } } /// <summary> /// 上传文件 /// </summary> /// <param name="file">通过form表达提交的文件</param> /// <param name="virpath">文件要保存的虚拟路径</param> public static void uploadFile(HttpPostedFile file, string virpath) { if (file.ContentLength > 1024 * 1024 * 6) { throw new Exception("文件不能大于6M"); } string imgtype = Path.GetExtension(file.FileName); //imgtype对上传的文件进行限制 if (imgtype != ".zip" && imgtype != ".mp3") { throw new Exception("只允许上传zip、rar....文件"); } string dirFullPath= HttpContext.Current.Server.MapPath(virpath); if (!Directory.Exists(dirFullPath))//如果文件夹不存在,则先创建文件夹 { Directory.CreateDirectory(dirFullPath); } file.SaveAs(dirFullPath + file.FileName); }
2. Ajax file asynchronous Upload:
Note: Since there is a form upload, why do you need ajax upload? Because during the form upload process, the entire page is refreshed! Ajax asynchronous upload can refresh only the local position. Let’s take a brief look at ajax upload! html client part:<head> <script src="jquery-2.1.4.js"></script> <script> $(function () { $("#upload").click(function () { $("#imgWait").show(); var formData = new FormData(); formData.append("myfile", document.getElementById("file1").files[0]); $.ajax({ url: "upload.ashx", type: "POST", data: formData, /** *必须false才会自动加上正确的Content-Type */ contentType: false, /** * 必须false才会避开jQuery对 formdata 的默认处理 * XMLHttpRequest会对 formdata 进行正确的处理 */ processData: false, success: function (data) { if (data.status == "true") { alert("上传成功!"); } if (data.status == "error") { alert(data.msg); } $("#imgWait").hide(); }, error: function () { alert("上传失败!"); $("#imgWait").hide(); } }); }); }); </script> </head> <body> 选择文件:<input type="file" id="file1" /><br /> <input type="button" id="upload" value="上传" /> <img src="wait.gif" style="display:none" id="imgWait" /> </body>
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; if (context.Request.Files.Count > 0) { HttpPostedFile file1 = context.Request.Files["myfile"]; helper.uploadFile(file1, "~/upload/"); //这里引用的是上面封装的方法 WriteJson(context.Response, "true", ""); } else { WriteJson(context.Response, "error", "请选择要上传的文件"); } }
public static void WriteJson(HttpResponse response, string status1, string msg1, object data1 = null) { response.ContentType = "application/json"; var obj = new { status = status1, msg = msg1, data = data1 }; string json = new JavaScriptSerializer().Serialize(obj); response.Write(json); }
How does AjaxFileUpload dynamically add a file upload box
Practical summary of Ajax and jsonp in the project
The above is the detailed content of ajax file asynchronous implementation of form upload. For more information, please follow other related articles on the PHP Chinese website!

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



How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Forms are an integral part of writing a website or application. Laravel, as a popular PHP framework, provides rich and powerful form classes, making form processing easier and more efficient. This article will introduce some tips on using Laravel form classes to help you improve development efficiency. The following explains in detail through specific code examples. Creating a form To create a form in Laravel, you first need to write the corresponding HTML form in the view. When working with forms, you can use Laravel
