BOOTSTRAP-WYSIWYG combining Ajax to realize real-time refresh of picture upload _javascript skills

Source: Internet
Author: User
Tags unsupported

Recently due to project requirements, to implement a front-end text editing box, with the image upload real-time view of the function. Compared with several plug-ins on the web, the first is Baidu's ueitor, found that the framework is too large, a small framework to introduce so many files is not what I want to see, and then jquery Easyui, although the personal version of the free, but the project belongs to the business, seems to use the commercial version of the framework and inappropriate. Considering that the front-end of the project is mainly built on the basis of Bootstrap, the final selection of the BOOTSTRAP-WYSIWYG plug-in, it is very concise, lightweight and strong scalability.

The introduction of BOOTSTRAP-WYSIWYG and the realization of the text editing function is very convenient, but, I notice that the image upload is implemented with FILEAPI. For most Web sites, although using FILEAPI to achieve a no upload preview user experience is very good, but when the real database, we still want to be able to store pictures in the server's static path, rather than a string of pictures. In short, we need to rewrite the BOOTSTRAP-WYSIWYG (hereinafter referred to as WY) slightly.

First we look at the picture on the page control, other controls skip, check the source, it is easy to find the following code:

<div class= "Btn-group" >
 <a class= "btn" title= "Insert picture (or just drag & drop)" id= "PICTUREBTN" >
 <i class= "icon-picture" ></i></a>
  <input type= "file" data-role= "Magic-overlay" 
   data-target= "#pictureBtn"
  data-edit= "Insertimage"/>
</div>

To do this, the Data-role,data-target property is a predefined event in the bootstrap, where we can understand the layout-related, regardless. The key point is, the third attribute Data-edit,bootstrap does not have this event, observes Bootstrap-wysiwyg.js, can discover such some code:

Toolbar.find (' input[type=file][data-' + options.commandrole + '] ')
   . Change (...
   ) ...
Commandrole: ' Edit ',

That is, the property is actually implemented for convenience of selectors, which is equivalent to adding a listener event to the picture button.

We then look at the implementation of the WY Picture Preview, the first step, as shown in the code above, the listener captures the Fileinput change event, responds, and invokes the Insertfiles function

Restoreselection ();
if (This.type = = ' file ' && this.files && this.files.length > 0) {
 insertfiles (this.files);
}
saveselection ();
His.value = ';

Find the Insertfiles function

Insertfiles = function (files) {
  editor.focus ();
  $.each (Files, function (idx, fileInfo) {
   if (/^image\//.test (Fileinfo.type)) {
   $.when readfileintodataurl ( FileInfo)). Done (function (dataurl) {
    execcommand (' Insertimage ', dataurl);
   }). Fail (function (e) {
    options.fileuploaderror ("File-reader", e);
   });
   } else {
   Options.fileuploaderror ("Unsupported-file-type", Fileinfo.type);
   }
  );
  }

We notice that it uses jquery's $. Deferred () method, first called a Readfileintodataurl method, after success through the ExecCommand method of the self-installed to output the picture to the text box. The picture is actually a tag, except that the SRC attribute is a string representation of the picture. So what we have to do is actually after the listener triggered, upload the file, get the picture of SRC, and then the link to the ExecCommand method.

Because the author is not particularly familiar with the deferred, so still adopt a more common callback mode

Observe how ajaxfileupload is invoked:

$.ajaxfileupload ({
  URL: ...,
  secureurl:false,
  fileelementid: ...,
  dataType: "JSON",
  success: function (obj) {...}
  ,
  error:function () {
   ...
  }}
  );

There are two required attributes, URLs, and Fileelementid, and rewriting ajaxfileupload is undesirable in order to maintain the correctness of dependencies. But since the WY control is implemented by the listener, it is unrealistic to pass the parameters through the function, so we need to define some properties for the input box to achieve our goal.

Add some properties to Fileinput

<input type= "File" id= "Pictureinput" name= "Picture" data-role= "Magic-overlay" data-target= "
   #pictureBtn"
   data-edit= "Insertimage" action= "..."/>

ID used as a Fileelementid,name property is also necessary, mainly for the background value named, action is the picture needs to be submitted to the URL

Define a function named Uploadfiletoserver in Bootstrap-wysiwyg.js, and the function is formatted as follows:

var uploadfiletoserver = function (ID, action, callback) {
 $.ajaxfileupload ({
  url:action,
  secureurl:false ,
  Fileelementid:id,
  dataType: ' json ',
  success:function (obj) {
  if (obj.status) {
   callback ( OBJ.IMGSRC);
  } else
   options.fileuploaderror ("Server-internal-exception",
    obj.message);
  },
  error:function ( ) {
  Options.fileuploaderroe ("Upload-failure", "");
  }
 });

The Insertfiles method is rewritten as follows:

Insertfiles = function (files, IDs, action) {
  editor.focus ();
  $.each (Files, function (idx, fileInfo) {
  if (/^image\//.test (Fileinfo.type)) {
   /
   * $.when ( Readfileintodataurl (FileInfo)). Done (function (dataurl) {
   * execcommand (' insertimage ', Dataurl);}). Fail (function (e) {
   * Options.fileuploaderror ("File-reader", e);});
   * *
   Uploadfiletoserver (ID, action, function (SRC) {
   execcommand (' insertimage ', src);
   });
  } else {
   options.fileuploaderror ("Unsupported-file-type",
    fileinfo.type);
  }
  );

At the same time make certain changes to the listener to get the necessary attributes

Toolbar.find (' input[type=file][data-' + options.commandrole + '] ')
  . Change (
   function () {
    Restoreselection ();
    if (This.type = = ' file ' && this.files
     && this.files.length > 0) {
     insertfiles (this.files, $ ( This). attr (' id '),
      $ (this). attr (' action ');
    }
    Saveselection ();
    This.value = ';
    } ';

The main increase is two parameter locations.

So, the rewrite is done, and note that to make sure that you do it correctly, refer to Ajaxfileupload.js before the control.

If you want to further study, you can click here to learn, and then attach 3 wonderful topics:

Bootstrap Learning Course

Bootstrap Practical Course

Bootstrap Plugin Usage Tutorial

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.