Home Web Front-end JS Tutorial Tutorial on how to use JavaScript to preview and upload images without refreshing the page

Tutorial on how to use JavaScript to preview and upload images without refreshing the page

Aug 06, 2017 pm 03:28 PM
javascript js page

This article mainly introduces in detail the JavaScript function of uploading preview images without refreshing. It has certain reference value. Interested friends can refer to

How to implement the function of uploading without refreshing? Handwritten non-refresh upload requires two things, FormData and FileReader.

FileReader is used for image browsing.

FormData is used for ajax requests.

html code

First create a container for the form and image


##

  <form enctype="multipart/form-data" id="oForm">
    <input type="file" name="file" id="file" onchange="readAsDataURL()" />
    <input type="button" value="提交" onclick="doUpload()" />
  </form>
  <p>
    <img alt="" id="img"/>
  </p>
Copy after login

javascript code

FormData:

The FormData object can be used to assemble a set of key/value pairs for sending requests using XMLHttpRequest. It makes sending form data more flexible and convenient because it can be used independently of the form. If you set the form's encoding type to multipart/form-data, the data format transmitted through FormData is the same as the data format transmitted by the form through the submit() method.

Here the FormData object is used to obtain all the input data in the form, and then use an ajax request to send the data to the specified url, so that there will be no jump when the form is submitted.


  function doUpload() { 
     var formData = new FormData($( "#oForm" )[0]); 
     console.log(formData); 
     $.ajax({ 
       url: &#39;pp&#39;, 
       type: &#39;POST&#39;, 
       data: formData, 
       async: false, 
       cache: false, 
       contentType: false, 
       processData: false, 
       success: function (returndata) { 
         console.log(returndata); 
       }, 
       error: function (returndata) { 
         console.log(returndata); 
       } 
     }); 
  }
Copy after login

FileReader:

The FileReader object allows web applications to asynchronously read files stored in The contents of a file (or raw data buffer) on the user's computer, using a File or Blob object to specify the file or data to be read.

Here the FileReader object is used to obtain the image from file and convert the image into Data URL form to display in the pre-created container.


function readAsDataURL(){
  //检验是否为图像文件
    var file = document.getElementById("file").files[0];
    if(!/image\/\w+/.test(file.type)){
      alert("看清楚,这个需要图片!");

      return false;
    }else{
    var reader = new FileReader();
    //将文件以Data URL形式读入页面
    reader.readAsDataURL(file);
    reader.onload=function(e){
      var result=document.getElementById("img");
      //显示文件
      result.src= this.result ;
    }
  }
}
Copy after login

The above is the detailed content of Tutorial on how to use JavaScript to preview and upload images without refreshing the page. 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)

How to copy a page in Word How to copy a page in Word Feb 20, 2024 am 10:09 AM

Want to copy a page in Microsoft Word and keep the formatting intact? This is a smart idea because duplicating pages in Word can be a useful time-saving technique when you want to create multiple copies of a specific document layout or format. This guide will walk you through the step-by-step process of copying pages in Word, whether you are creating a template or copying a specific page in a document. These simple instructions are designed to help you easily recreate your page without having to start from scratch. Why copy pages in Microsoft Word? There are several reasons why copying pages in Word is very beneficial: When you have a document with a specific layout or format that you want to copy. Unlike recreating the entire page from scratch

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

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

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

How to quickly refresh a web page? How to quickly refresh a web page? Feb 18, 2024 pm 01:14 PM

Page refresh is very common in our daily network use. When we visit a web page, we sometimes encounter some problems, such as the web page not loading or displaying abnormally, etc. At this time, we usually choose to refresh the page to solve the problem, so how to refresh the page quickly? Let’s discuss the shortcut keys for page refresh. The page refresh shortcut key is a method to quickly refresh the current web page through keyboard operations. In different operating systems and browsers, the shortcut keys for page refresh may be different. Below we use the common W

How to implement page jump in 3 seconds: PHP Programming Guide How to implement page jump in 3 seconds: PHP Programming Guide Mar 25, 2024 am 10:42 AM

Title: Implementation method of page jump in 3 seconds: PHP Programming Guide In web development, page jump is a common operation. Generally, we use meta tags in HTML or JavaScript methods to jump to pages. However, in some specific cases, we need to perform page jumps on the server side. This article will introduce how to use PHP programming to implement a function that automatically jumps to a specified page within 3 seconds, and will also give specific code examples. The basic principle of page jump using PHP. PHP is a kind of

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to deal with the problem that Laravel page cannot display CSS correctly How to deal with the problem that Laravel page cannot display CSS correctly Mar 10, 2024 am 11:33 AM

"Methods to handle Laravel pages that cannot display CSS correctly, need specific code examples" When using the Laravel framework to develop web applications, sometimes you will encounter the problem that the page cannot display CSS styles correctly, which may cause the page to render abnormal styles. Affect user experience. This article will introduce some methods to deal with the failure of Laravel pages to display CSS correctly, and provide specific code examples to help developers solve this common problem. 1. Check the file path. First check the path of the CSS file.

See all articles