Home Web Front-end JS Tutorial Javascript implementation of asynchronous image upload method example

Javascript implementation of asynchronous image upload method example

Dec 06, 2017 am 11:07 AM
javascript js upload

How to write asynchronous image upload through javascript? In this article, we will share with you some example code javascript to implement asynchronous image upload. Let’s first look at the form submission part implemented by HTML code. When testing, you need to replace the test URL with your own, or you can directly write a local address to test.

html code:


1

2

3

4

5

6

7

<form id="uploadForm" action="http://storage.test.com/file/upload" method="post" enctype="multipart/form-data">

  <input type="hidden" name="key" id="key" value="VTZ18HM64#D_L3WX" />

  <input type="file" name="uploadFiles" value="" id="fileImage" multiple=&#39;multiple&#39; />

  <p class="upload_submit">

  <button type="button" id="fileSubmit" class="upload_btn">保存</button>

  </p>

</form>

Copy after login


js 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

47

48

49

50

51

52

53

54

55

56

57

58

59

var Fileupload = {

  fileInput: $("#fileImage").get(0),

  dragDrop: $("#fileDragArea").get(0),

  upButton: $("#fileSubmit").get(0),

  url: $("#uploadForm").attr("action"),

  })(),

  //文件上传

  funUploadFile: function() {

   var self = this;

   for (var i = 0, file; file = this.fileFilter[i]; i++) {

    (function(file) {

     var xhr = new XMLHttpRequest();

     if (xhr.upload) {

      // 上传中

      xhr.upload.addEventListener("progress", function(e) {

       self.onProgress(file, e.loaded, e.total);

      }, false);

      // 文件上传成功或是失败

      xhr.onreadystatechange = function(e) {

 

      if (xhr.readyState == 4) {

        if (xhr.status == 200) {

         self.onSuccess(JSON.parse(xhr.responseText));

         self.funDeleteFile(file);

         if (!self.fileFilter.length) {

          //全部完毕

          self.onComplete();

         }

        } else {

         self.onFailure(file, xhr.responseText);

        }

       }

      };

      //准备FormData对象

      var myForm = document.getElementById(&#39;uploadForm&#39;);

      //将文件放入FormData对象中

      formData = new FormData(myForm);

 

      // 开始上传

      xhr.open("POST", self.url, true);

      xhr.send(formData);

     }

    })(file);

   }

  },

  init: function() {

   var self = this;

   //上传按钮提交

   if (this.upButton) {

    console.log(&#39;提示: 当前存储服务器地址&#39;, this.url)

    this.upButton.addEventListener("click", function(e) {

     self.funUploadFile(e);

    }, false);

   }

   self.bindEvent();

  }

 };

 Fileupload = $.extend(Fileupload);

 Fileupload.init();

Copy after login


FormData asynchronously uploads files


1

<input type="file" id="file">

Copy after login


1. Create FormData and put the file to be uploaded


1

2

3

4

5

6

//准备FormData对象

var formData = new FormData(),

 uploadFile = document.getElementById(&#39;file&#39;);

  

//将文件放入FormData对象中

formData.append(&#39;file&#39;, uploadFile.files[0]);

Copy after login


2. Send FormData data to the server through xhr to implement file upload


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

//创建xhr对象

var xhr = new XMLHttpRequest();

 

//监听文件上传进度

xhr.upload.onprogress = function(evt){

 //lengthComputabel: 文件长度是否可计算

 if(evt.lengthComputable){

  //evt.loaded: 已下载的字节数

  //evt.total: 文件总字节数

  var percent = Math.round(evt.loaded*100/evt.total);

  console.log(percent);

 }

}

 

//监听文件传输开始

xhr.onloadstart = function(evt){

  xhr.abort() //终止上传

}

 

//监听ajax成功完成事件

xhr.onload = function(evt){

 ...

}

 

//监听ajax错误事件

xhr.onerror = function(evt){

 ...

}

 

//监听ajax被中止事件

xhr.onabort = function(evt){

 ...

}

 

//监听传输结束事件: 不管成功或者失败都会触发

xhr.onloaded = function(evt){

 ...

}

  

//*发起ajax请求数据

xhr.open(&#39;POST&#39;, &#39;/url&#39;, true);

xhr.send(formData);

Copy after login

The above content is an example of asynchronous image upload method in JavaScript. I hope it can help everyone.

Related recommendations:

php+js implements asynchronous image uploading example sharing

JavaScript uses FileReader to complete image uploading and previewing function introduction

Detailed explanation of how node.js implements simple image upload code

The above is the detailed content of Javascript implementation of asynchronous image upload method example. 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
1654
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

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 improve computer upload speed How to improve computer upload speed Jan 15, 2024 pm 06:51 PM

Upload speed becomes very slow? I believe this is a problem that many friends will encounter when uploading things on their computers. If the network is unstable when using a computer to transfer files, the upload speed will be very slow. So how can I increase the network upload speed? Below, the editor will tell you how to solve the problem of slow computer upload speed. When it comes to network speed, we all know that the speed of opening web pages, download speed, and upload speed are also very critical. Especially some users often need to upload files to the network disk, so a fast upload speed will undoubtedly save you a lot of money. Less time, what should I do if the upload speed is slow? Below, the editor brings you pictures and texts on how to deal with slow computer upload speeds. How to solve the problem of slow computer upload speed? Click "Start--Run" or "Window key"

See all articles