search
HomeBackend DevelopmentPHP TutorialHow to implement Ajax upload image and preview function

How to implement Ajax upload image and preview function

Dec 25, 2017 am 10:17 AM
ajaxFunctionPreview

最近有几个小项目用到了easyUI,一开始决定使用easyUI就注定了项目整体上前后端分离,基本上所有的请求都采用Ajax来完成。在文件上传的时候用到了Ajax上传文件,以及图片在上传之前的预览效果,解决了这两个小问题,和小伙伴们分享下,希望能帮助到大家。

上传之前的预览

方式一

先来说说图片上传之前的预览问题。这里主要采用了HTML5中的FileReader对象来实现,关于FileReader对象,如果小伙伴们不了解,可以查看这篇文章HTML5学习之FileReader接口。我们来看看实现方式:

nbsp;html>


 <meta>
 <title>Ajax上传文件</title>
 <script></script>


用户名:<input><br>
用户图像:<input><br>
<p></p>
<input>
<script>
 $("#btnClick").click(function () {
  var formData = new FormData();
  formData.append("username", $("#username").val());
  formData.append("file", $("#userface")[0].files[0]);
  $.ajax({
   url: &#39;/fileupload&#39;,
   type: &#39;post&#39;,
   data: formData,
   processData: false,
   contentType: false,
   success: function (msg) {
    alert(msg);
   }
  });
 });
 function preview(file) {
  var prevp = document.getElementById(&#39;preview&#39;);
  if (file.files && file.files[0]) {
   var reader = new FileReader();
   reader.onload = function (evt) {
    prevp.innerHTML = &#39;<img  src="/static/imghwm/default1.png"  data-src="&#39; + evt.target.result + &#39;"  class="lazy"   / alt="How to implement Ajax upload image and preview function" >&#39;;
   }
   reader.readAsDataURL(file.files[0]);
  } else {
   prevp.innerHTML = &#39;<p class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\&#39;&#39; + file.value + &#39;\&#39;">&#39;;
  }
 }
</script>

这里对于支持FileReader的浏览器直接使用FileReader来实现,不支持FileReader的浏览器则采用微软的滤镜来实现(注意给图片上传的input标签设置onchange函数)。

实现效果如下:

How to implement Ajax upload image and preview function

方式二

除了这种方式之外我们也可以采用网上现成的一个jQuery实现的方式。这里主要参考了这里。

不过由于原文年代久远,里边使用的$.browser.msie从jQuery1.9就被移除掉了,所以如果我们想使用这个得做一点额外的处理,我修改后的uploadPreview.js文件内容如下:

jQuery.browser={};(function(){jQuery.browser.msie=false; jQuery.browser.version=0;if(navigator.userAgent.match(/MSIE ([0-9]+)./)){ jQuery.browser.msie=true;jQuery.browser.version=RegExp.$1;}})();
jQuery.fn.extend({
 uploadPreview: function (opts) {
  var _self = this,
   _this = $(this);
  opts = jQuery.extend({
   Img: "ImgPr",
   Width: 100,
   Height: 100,
   ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
   Callback: function () {}
  }, opts || {});
  _self.getObjectURL = function (file) {
   var url = null;
   if (window.createObjectURL != undefined) {
    url = window.createObjectURL(file)
   } else if (window.URL != undefined) {
    url = window.URL.createObjectURL(file)
   } else if (window.webkitURL != undefined) {
    url = window.webkitURL.createObjectURL(file)
   }
   return url
  };
  _this.change(function () {
   if (this.value) {
    if (!RegExp("\.(" + opts.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
     alert("选择文件错误,图片类型必须是" + opts.ImgType.join(",") + "中的一种");
     this.value = "";
     return false
    }
    if ($.browser.msie) {
     try {
      $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
     } catch (e) {
      var src = "";
      var obj = $("#" + opts.Img);
      var p = obj.parent("p")[0];
      _self.select();
      if (top != self) {
       window.parent.document.body.focus()
      } else {
       _self.blur()
      }
      src = document.selection.createRange().text;
      document.selection.empty();
      obj.hide();
      obj.parent("p").css({
       'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
       'width': opts.Width + 'px',
       'height': opts.Height + 'px'
      });
      p.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src
     }
    } else {
     $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
    }
    opts.Callback()
   }
  })
 }
});

然后在我们的html文件中引入这个js文件即可:

nbsp;html>


 <meta>
 <title>Ajax上传文件</title>
 <script></script>
 <script></script>


用户名:<input><br>
用户图像:<input><br>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/054/025/3a26f601966dfd207ad79c0227defade-1.png?x-oss-process=image/resize,p_40" class="lazy" alt="How to implement Ajax upload image and preview function" ></p>
<input>
<script>
 $("#btnClick").click(function () {
  var formData = new FormData();
  formData.append("username", $("#username").val());
  formData.append("file", $("#userface")[0].files[0]);
  $.ajax({
   url: &#39;/fileupload&#39;,
   type: &#39;post&#39;,
   data: formData,
   processData: false,
   contentType: false,
   success: function (msg) {
    alert(msg);
   }
  });
 });
 $("#userface").uploadPreview({Img: "ImgPr", Width: 120, Height: 120});
</script>

这里有如下几点需要注意:

1.HTML页面中要引入我们自定义的uploadPreview.js文件

2.预先定义好要显示预览图片的img标签,该标签要有id。

3.查找到img标签然后调用uploadPreview函数

执行效果如下:

How to implement Ajax upload image and preview function

Ajax上传图片文件

Ajax上传图片文件就简单了,没有那么多方案,核心代码如下:

 var formData = new FormData();
  formData.append("username", $("#username").val());
  formData.append("file", $("#userface")[0].files[0]);
  $.ajax({
   url: '/fileupload',
   type: 'post',
   data: formData,
   processData: false,
   contentType: false,
   success: function (msg) {
    alert(msg);
   }
  });

核心就是定义一个FormData对象,将要上传的数据包装到这个对象中去。然后在ajax上传数据的时候设置data属性就为formdata,processData属性设置为false,表示jquery不要去处理发送的数据,然后设置contentType属性的值为false,表示不要设置请求头的contentType属性。OK,主要就是设置这三个,设置成功之后,其他的处理就和常规的ajax用法一致了。

后台的处理代码大家可以在文末的案例中下载,这里我就不展示不出来了。

相关推荐:

MySQL+SSM+Ajax上传图片问题的分析(图)

PHP类似AJAx上传图片简单实例_PHP教程

JS实现上传图片并且能够预览的实例详解

The above is the detailed content of How to implement Ajax upload image and preview function. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.