Home Web Front-end JS Tutorial angularJS+Ionic uploads images on the mobile terminal (with code)

angularJS+Ionic uploads images on the mobile terminal (with code)

Apr 17, 2018 am 11:22 AM
javascript upload

This time I bring you angularJS Ionic uploads images on the mobile terminal (with code), angularJS Ionic uploads images on the mobile terminal What are the precautions, here are Let’s take a look at practical cases.

In front-end development, we often encounter the problem of image uploading. There are many solutions online, but some image uploading plug-ins have some attached plug-ins, so because of an image uploading problem, you may need to If other plug-ins are introduced into the project, the project will become nondescript over time, and sometimes there will be some conflicts between plug-ins, so we can write a method of uploading images ourselves.

Today’s demo is a mobile WeChat public account project that I made for a friend. The project architecture uses Angular Ionic because it is much more convenient to operate jQuery on the DOM, but jQuery is relatively heavy, so in the end I chose to use the lightweight zepto to operate the project DOM. Perform operations.

js structure:

function1:

$scope.imgList = [];
$scope.setUploader = function () {
  var files = document.getElementById('photo');
  files.click();
  $(files).unbind().on('change',function (e) {
    var file = e.target.value;
    if (!/.(jpg|jpeg|png|GIF|JPG|png)$/.test(file)) {
      common.toast('图片类型必须是jpeg,jpg,png中的一种');
      return false;
    };
    fsubmit();
    readAsBinaryString();
  });
};
Copy after login

function2:

function fsubmit() {
  var itemImg = {};
  var form=document.getElementById("form1");
  console.log('form',form)
  var formData=new FormData(form);
  formData.append('wxdesigner_sid',$.fn.cookie('wxdesigner_sid'));
  formData.append('id',$scope.masterInfo.id);
  formData.append('pc','1');
  var oReq = new XMLHttpRequest();
  oReq.onreadystatechange=function(){
    if(oReq.readyState==4){
      if(oReq.status==200){
        var json=JSON.parse(oReq.responseText);
        console.log(json)
        if(json.Success) {
          itemImg = json.Data;
          $scope.imgList=itemImg;
          console.log($scope.imgList)
          $scope.$apply();
          itemImg = {};
        }
      }
    }
  };
  console.log(oReq)
  console.log(formData)
  oReq.open("POST", common.api+"Wxdesigner/Designer/uploadworks");
  oReq.send(formData);
  return false;
};
//判断浏览器是否支持FileReader接口
if(typeof FileReader == 'undefined'){
  //使选择控件不可操作
  file.setAttribute("disabled","disabled");
}
Copy after login

function3:

function readAsBinaryString(){
  var file = document.getElementById('photo').files[0];
  console.log(file)
  var reader = new FileReader();
  //将文件以二进制形式读入页面
  reader.readAsDataURL(file);
  reader.onload=function(f){
    $scope.masterInfo.thumblist.push(f.currentTarget.result)
    console.log($scope.masterInfo)
    $scope.$apply()
  }
}
Copy after login

The DOM layer of the entire image upload is very simple, a form plus a function (function1) that triggers the form. The click event of is obtained in function1, and a judgment will be made when selecting an image. If the range of the supported image types is exceeded, a reminder will be issued.

Then call function2 and function3 later.

Get the form object in function2, then create a FormData object, pass the obtained form into FormData, and then append some parameters for uploading images. Create another new XMLHttpRequest object, then open the XHR request interface, and send(formData) passes parameters to the interface.

At this time, the interface is sent successfully.

The four parameters here are the four parameters in formData

The interface accordingly succeeds.

There is a problem here. The image upload is successfully written to the database, but at this time it needs to be displayed locally to the user, but the web page cannot directly access the local image of the device, so we need a FIleReader object to read the uploaded image file as a DataURL. Shown locally.

First, New a FileReader object, and then pass the obtained input file object into the FileReader's readAsDataURL() method. This method reads the file as DataURL.

Then call the onload method of FileReader. The result of this method will have the converted url, so we can get this url, which is actually base64 encoded. Then push to the end of the picture list

This solves the problem. The front end displays local pictures and the pictures are also written to the database. When the page is refreshed again, the data in the database is obtained.

Of course, this is just a method, mobile image upload Plug-ins abound, and there are even various drag-and-drop image upload plug-ins. This is suitable for simple functions of image upload in projects without introducing plug-ins.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the scrolling behavior of Vue-Router

Particles.js implements particle dynamic background animation

Detailed explanation of the use of routing meta information of Vue-router

The above is the detailed content of angularJS+Ionic uploads images on the mobile terminal (with code). 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
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
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.

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

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"

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

See all articles