Home Backend Development PHP Tutorial Detailed explanation of form upload implementation ajax file asynchronous upload

Detailed explanation of form upload implementation ajax file asynchronous upload

Dec 25, 2017 am 10:25 AM
ajax upload accomplish

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 is mainly for processing small file uploads! This article mainly introduces the form upload function and file upload function implementation in detail. Ajax file asynchronous upload has certain reference value. Interested friends can refer to it. I hope it can help everyone.

Resource download:

1. jQuery official download address: https://jquery.com/download/

1. Form upload:

html Client part:


1

2

3

4

<form action="upload.ashx" method="post" enctype="multipart/form-data">

    选择文件:<input type="file" name="file1" /><br />

    <input type="submit" value="上传" />

  </form>

Copy after login

General handler server side:


1

2

3

4

5

6

7

public void ProcessRequest(HttpContext context)

    {

      context.Response.ContentType = "text/plain";

      HttpPostedFile file1 = context.Request.Files["file1"];

      helper.uploadFile(file1, "~/upload/");//这里就是对相应方法进行调用

      context.Response.Write("ok");//提示执行成功

    }

Copy after login

Encapsulation of upload code:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

/// <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);

    }

Copy after login

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:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

<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>

Copy after login

General handler server side:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

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", "请选择要上传的文件");

   }

  }

Copy after login

json Code encapsulation:


1

2

3

4

5

6

7

8

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);

    }

Copy after login

Related recommendations:

Ajax multiple methods of asynchronous file upload

How to implement asynchronous uploading of files using native js

Detailed explanation of the function of asynchronous uploading of images and text using php+ajax

The above is the detailed content of Detailed explanation of form upload implementation ajax file asynchronous upload. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

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

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

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.

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

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 upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

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.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

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.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

See all articles