Home Web Front-end JS Tutorial How to preview images locally when uploading them

How to preview images locally when uploading them

Mar 17, 2018 am 11:53 AM
how local Preview

This time I will show you how to preview locally first when uploading pictures, and what are the precautions to implement local preview when uploading pictures. The following is a practical case, let's take a look.

The FileReader object allows a Web application to asynchronously read the contents of a file (or raw data buffer) stored on the user's computer, using a File or Blob object to specify the file or data to be read. This article will introduce to you the use of FileReader in JS to realize the local preview function before uploading pictures. Friends who need it can refer to the introduction

What I usually do When uploading and previewing images, if there are no special requirements, just upload the image directly to the background. After success, get the URL and then render it on the page. This will not cause any problem when the image is relatively small. If it is larger, it will be slower to view. It’s time to preview, and junk files are generated, so it’s better to preview it locally before uploading. When I was working on a project and looking for a plug-in, I knew that the pure front-end could realize local preview of images, but when I was asked about it during the interview today, I was confused, and then I accidentally discovered the implementation on the computer desktop. demo, and then checked the API based on the demo, and briefly summarized it:

First you have to get the File object

When using input TagWhen uploading pictures, the event object will contain a collection of file objects

event.target.files

##The core is the FileReader object

According to MDN: The FileReader object allows a web application to asynchronously read the contents of a file (or raw data buffer) stored on the user's computer. Use a File or Blob object to specify the file or data to read.

First, as a

constructor

Get an instance object of FileReader

var freader = new FileReader();
Copy after login
Use the readAsDataURL() method to read the specified content

freader.readAsDataURL(file);
Copy after login
Finally, a Event processing is equivalent to monitoring the reading progress. Here we render the image when the reading is completed, so use onload

freader.onload = function(e) { console.log(e); myImg.setAttribute('src', e.target.result); }
Copy after login
After the frame loading is completed, the final result is a base64 encoded src address, the specific reason why I will check it out next time and then write a special article about base64 encoding

Complete code

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
 <form action=""> 
 <input type="file" name="files" id="fileTog" accept="image/*" multiple="multiple" onchange="changImg(event)"> 
 <img alt="暂无图片" id="myImg" src="" height="100px" width="100px"> 
 </form>
 <script>
 function changImg(e){ 
 var myImg = document.getElementById('myImg');
 for (var i = 0; i < e.target.files.length; i++) { 
 var file = e.target.files[i]; 
 console.log(file); 
 if (!(/^image\/.*$/i.test(file.type))) { 
  continue; //不是图片 就跳出这一次循环 
 } 
 //实例化FileReader API 
 var freader = new FileReader(); 
 freader.readAsDataURL(file); 
 freader.onload = function(e) { 
  console.log(e);
  myImg.setAttribute(&#39;src&#39;, e.target.result); 
 } 
 } 
 }
 </script>
</body>
</html>
Copy after login
I believe you have mastered the method after reading the case in this article, please pay attention for more exciting things Other related articles on php Chinese website!

Recommended reading:

Set cookie expiration, automatic update and automatic acquisition

Use import and require to package JS

How to deal with the option overlay of select

The above is the detailed content of How to preview images locally when uploading them. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 add local music to soda music How to add local music to soda music Feb 23, 2024 pm 07:13 PM

How to add local music to Soda Music? You can add your favorite local music to Soda Music APP, but most friends don’t know how to add local music. Next is the graphic tutorial on how to add local music to Soda Music brought by the editor. , interested users come and take a look! Tutorial on using soda music. How to add local music to soda music. 1. First open the soda music APP and click on the [Music] function area at the bottom of the main page; 2. Then enter the play page and click the [three dots] icon in the lower right corner; 3. Finally Expand the function bar below and select the [Download] button to add it to local music.

How to add watermark and save remote images after saving them locally in PHP? How to add watermark and save remote images after saving them locally in PHP? Jul 11, 2023 pm 11:48 PM

How to add watermark and save remote images after saving them locally in PHP? In PHP development, we often encounter the need to save remote images locally. Sometimes, we may also need to add a watermark to the saved image to protect copyright or add additional information. This article will introduce how to use PHP to save remote pictures to local and add watermarks to the saved pictures. 1. Save remote images to local. First, we need to use PHP's file operation function to save remote images to local. Here is a simple example code: &

How to implement image scrolling and thumbnail preview in Vue? How to implement image scrolling and thumbnail preview in Vue? Aug 18, 2023 pm 01:51 PM

How to implement image scrolling and thumbnail preview in Vue? In Vue projects, we often need to display a large number of pictures, and hope that users can browse and preview these pictures easily. This article will introduce how to use Vue components to implement image scrolling and thumbnail preview functions. First, we need to install and introduce the appropriate Vue library to facilitate image scrolling and thumbnail preview. In this example, we will use vue-awesome-swiper and vue-image-preview two libraries to implement

Early Access to Future Features Safari Technology Preview 173 Released Early Access to Future Features Safari Technology Preview 173 Released Jul 02, 2023 pm 01:37 PM

Apple today released Safari Technology Preview version 173, which covers some features that may be launched in Safari 17. This version is suitable for macOS Sonoma beta version and macOS Ventura system. Interested users can download it from the official website. Safari Technology Preview version 173 adds a feature flag block in settings, replacing the experimental feature in the original development menu. This section allows developers to quickly search for specific features and marks the status as "stable", "available for testing", "preview" or "developer" in different ways. The redesigned development menu makes it easier for creators to find key tools for building web pages, web apps, web content in other apps,

Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Jan 02, 2024 pm 08:54 PM

What are the employment prospects of clinical pharmacy at Harbin Medical University? Although the national employment situation is not optimistic, pharmaceutical graduates still have good employment prospects. Overall, the supply of pharmaceutical graduates is less than the demand. Pharmaceutical companies and pharmaceutical factories are the main channels for absorbing such graduates. The demand for talents in the pharmaceutical industry is also growing steadily. According to reports, in recent years, the supply-demand ratio for graduate students in majors such as pharmaceutical preparations and natural medicinal chemistry has even reached 1:10. Employment direction of clinical pharmacy major: After graduation, students majoring in clinical medicine can engage in medical treatment, prevention, medical research, etc. in medical and health units, medical research and other departments. Employment positions: Medical representative, pharmaceutical sales representative, sales representative, sales manager, regional sales manager, investment manager, product manager, product specialist, nurse

Win11 apk installation guide Win11 apk installation guide Jan 03, 2024 pm 10:24 PM

As we all know, Microsoft announced that win11 will be able to run Android applications and install local apk. However, after updating win11, users found that they did not know how to install the local apk. In fact, this is because Microsoft has not yet implemented this feature for win11. It is necessary Wait for the function to be installed before you can use it. How to install local apk in win11: 1. According to Microsoft, after win11 has installed this function, you can directly double-click the downloaded apk file to install it directly. 2. After the installation is completed, users can also run it directly in the system. 3. Although it is now the official version of win11, Microsoft has not yet implemented this feature for win11. 4. So if the user wants to use win11

How to implement form image upload and preview in Vue form processing How to implement form image upload and preview in Vue form processing Aug 10, 2023 am 11:57 AM

How to implement form image upload and preview in Vue form processing Introduction: In modern web applications, form processing is a very common requirement. One common requirement is to allow users to upload images and preview them in a form. As a front-end framework, Vue.js provides us with a wealth of tools and methods to achieve this requirement. In this article, I will show you how to implement image upload and preview functions in Vue form processing. Step 1: Define Vue components First, we need to define a Vue group

How to implement image upload and preview in uniapp How to implement image upload and preview in uniapp Oct 21, 2023 am 11:48 AM

How to implement image upload and preview in uniapp In modern social network and e-commerce applications, image upload and preview functions are very common requirements. This article will introduce how to implement the image upload and preview functions in uniapp, and give specific code examples. 1. Implementation of the image upload function In the uniapp project, you first need to add an image upload component to the page, as shown below: &lt;template&gt;&lt;view&gt;&lt;im

See all articles