Best use of bootstrap fileinput.js File Upload component _javascript tips

Source: Internet
Author: User
Tags button type

This article describes how to use the bootstrap fileinput.js (the best file Upload component) for picture display, upload, including Springmvc back-end file preservation.

First, demo

Second, the introduction of Plug-ins

<link type= "Text/css" rel= "stylesheet" href= "${ctx}/components/fileinput/css/fileinput.css"/>
<script type= "Text/javascript" src= "${ctx}/components/fileinput/js/fileinput.js" ></script>
<script type= "Text/javascript" src= "${ctx}/components/fileinput/js/fileinput_locale_zh.js" ></script>

Http://plugins.krajee.com/file-input, this is its official document, which has a download address.

Third, the page

<input type= "file" name= "image" class= "ProjectFile" value= "${deal.image}"/>

1. Type=file and Class=projectfile, indicating that it is the input file type.
2. Name specifies its fetch key in the background.
3. Value specifies the path of the picture when it is displayed.

Four, the page executes when loading

Projectfileoptions: {
 showupload:false,
 showremove:false,
 language: ' en ',
 allowedpreviewtypes: [' Image '],
 allowedfileextensions: [' jpg ', ' png ', ' gif '],
 maxfilesize:2000,
 },
//File Upload box
$ (' Input [Class=projectfile] '). each (the function () {
 var ImageUrl = $ (this). attr ("value");

 if (ImageUrl) {
 var op = $.extend ({
 initialpreview: [//Preview picture Settings
 " ',]
 }, projectfileoptions);

 $ (this). Fileinput (OP);
 } else {
 $ (this). Fileinput (projectfileoptions);
 }
});

1. Obtain the corresponding input file through jquery, and then execute the Fileinput method.
2. Showupload settings whether there is an upload button.
3. Language designation of Chinese
4. Allowedfiletypes, allowedfileextensions do not know why did not play the effect?
5. maxfilesize Specify upload file size

Five, form forms with file files are submitted via Ajax

Let's take a look at the form layout with file form.

 <form class=" Form-horizontal required-validate "action=" ${ctx}/save? Callbacktype=confirmtimeoutforward "enctype=" Multipart/form-data "method=" POST "onsubmit=" Return IframeCallback ( This, Pageajaxdone) "> <div class=" Form-group "> <label for=" "class=" Col-md-1 Control-label "> Project cover </ label> <div class= "col-md-10 tl th" > <input type= "file" name= "image" class= "ProjectFile" value= "${deal.imag" e} "/> <p class= help-block" > supports JPG, JPEG, PNG, GIF format, size not exceeding 2.0m</p> </div> </div> <div clas s= "Form-group text-center" > <div class= "col-md-10 col-md-offset-1" > <button type= "Submit" class= "BTN btn-p Rimary BTN-LG "> Save </button> </div> </div> </form> 

1.enctype= "Multipart/form-data" is essential.
2.onsubmit= "Return Iframecallback (this, Pageajaxdone)" method, submitted form via Ajax (Iframecallback), and the callback function (Pageajaxdone) is invoked to do the next step when the upload succeeds.

For an introduction to Iframecallback, please refer to the data submitted by the form of the form summernote, which is not covered here.

Then we'll introduce the callback function Pageajaxdone.

function Pageajaxdone (JSON) {
 yunm.debug (JSON);
 Yunm.ajaxdone (JSON);

 if (json[yunm.keys.statuscode] = = YUNM.statusCode.ok) {
 var msg = json[yunm.keys.message];
 Pop-up message prompts
 yunm.debug (msg);

 if (YUNM.callbackType.confirmTimeoutForward = = Json.callbacktype) {
 $.showsuccesstimeout (msg, function () {
 window.location = Json.forwardurl;}
 );
 }
 }


Its main function is through the Ajaxdone method to handle the error message passed over the server, if the service-side operation is successful, then the message will be displayed, and then jump to the corresponding URL.

Six, Springmvc save pictures

Please refer to the back-end Springmvc file Save

PS: The above blog left a small doubt, has not been to study until a very good little partner gave me the following reminders:

Ihchenchen yesterday 13:42 published [Reply] allowedfiletypes, allowedfileextensions I know why there is no effect, because the Fileinput () method called two times, One last line in the Fileinput.js, and one time you wrote it Yourself (this). Fileinput (). In the fileinput.js is not set Allowedfiletypes, allowedfileextensions value. There are two ways to change: 1, the last few lines in the fileinput.js call comment out. 2, all use "data−" method to do, do not write (this). Fileinput ().

I am very grateful for Ihchenchen's well-meaning reminders, although his explanations do not solve my doubts, but I like this interactive technical exchange, before writing a lot of blogs, basically rarely occurs such a well-meaning and effective answer. This reminds me of Chinese programmers and foreign programmers, and the stories inside are shocking, with a bit of shame. So how to do "ask questions, get answers, no distractions." "is very precious, and" Ihchenchen "is full of this spirit!

Vi. FAQ allowedfiletypes, allowedfileextensions

Before puzzled why Bootstrap Fileinput Why set these two properties, no effect, in fact, is my own misunderstanding, now after a painful penetrating understanding suddenly dawned!

①, Allowedfiletypes

Allowedfiletypes
Array the list of allowed file types for upload. This with default is set to null which means the plugin supports all file types for upload. If An invalid The file type is found, then a validation the error message as set in Msginvalidfiletype would be raised. The following types as set in Filetypesettings are available for setup.

[' Image ', ' html ', ' text ', ' video ', ' Audio ', ' Flash ', ' object ']

Starting with the word "allowedfiletypes," which tells us the type of file we choose, it's easy to think of a picture like this:

In other words, we want "all files" at this time not "all files", but "image" and so on. Obviously this logic is not wrong, but it is not suitable for bootstrap fileinput!

Well, this time I can easily think that "allowedfiletypes" did not play a role!

But take a look at the picture below:

Roar, the original is in the file after you choose the type of check!

②, allowedfiletypes working principle

 $ (this). Fileinput ({
 showupload:false,
 showremove:false,
 language: ' en ',
 allowedpreviewtypes: [' Image '],
 allowedfiletypes: [' image '],
 allowedfileextensions: [' jpg ', ' png '],
 maxfilesize:2000,

 }) ;

With the Fileinput method we load a bootstrap fileinput component, how does the interior achieve allowedfiletypes?

By searching for the "allowedfiletypes" keyword in the fileinput.js file, we get the following code:

 var node = Ctr + I, Previewid = Previewinitid + "-" + node, istext, File = Files[i],
  caption = Self.slug (file.name), FileSize = (File.size | | 0)/1000, checkfile, fileextexpr = ',
  previewdata = objurl.createobjecturl (file), Filecoun t = 0, J, msg, Typ, chk,
  filetypes = self.allowedfiletypes, strtypes = IsEmpty (filetypes)? ': Filetypes.join (', '),
  fileext = self.allowedfileextensions, Strext = IsEmpty (fileext)? ': Fileext.join (', ');

Then we continue to see the following code:

 if (!isempty (filetypes) && IsArray (filetypes)) {for
     (j = 0; J < filetypes.length; j = 1) {
      Typ = file TYPES[J];
      Checkfile = Settings[typ];
      CHK = (checkfile!== undefined && checkfile (File.type, caption));
      FileCount + = IsEmpty (chk)? 0:chk.length;
     }
     if (FileCount = = 0) {
      msg = self.msgInvalidFileType.replace (' {name} ', caption). replace (' {types} ', strtypes);
      Self.iserror = ThrowError (msg, file, Previewid, i);
      return;
     }
    

We can see that the file type checking is happening on the Checkfile method, so what does the Checkfile method do?

 Defaultfiletypesettings = {
  image:function (VType, VName) {return
   (VType!==)? Undefined (' image. * '): Vname.match (/\. ( PNG|JPE?G) $/i);
  

The above is the content of checkfile.

    • This means that when we specify allowedfiletypes: [' image '], the type of image is checked.
    • Obviously we choose the TXT file does not belong to the image type, then will not match, appear above interface.
    • At the same time, the method tells us that when the allowedfiletypes is not specified: [' image '], and only specify allowedfileextensions: [' jpg ', ' png '], the Vname.match is executed (/\. PNG|JPE?G) $/i, that is, the file suffix type of check, this is very important ah, for us to introduce the next "Allowedfileextensions" Lay the foundation.

When does ③ and allowedfileextensions play a role

In the last section we discussed "Allowedfiletypes", incidentally said "Allowedfileextensions", then how to let the suffix to check it?

 $ (this). Fileinput ({
    showupload:false,
    showremove:false,
    language: ' en ',
    allowedpreviewtypes: [' Image '],
    allowedfileextensions: [' jpg ', ' png '],
    maxfilesize:2000,

   });

Fileinput component At this point, the attribute specified has no "allowedfiletypes" and specifies that the allowed suffix type is "[' jpg ', ' png ']", that is, if we choose a GIF picture, we will get an error.

The error expected to occur, then please pay special attention to:

Image:function (VType, VName) {return
   (vtype!== undefined)? Vtype.match (' image.* '): Vname.match (/\. ( PNG|JPE?G) $/i);
  },

The original code in the Fileinput.js file is as follows:

Image:function (VType, VName) {return
   (vtype!== undefined)? Vtype.match (' image.* '): Vname.match (/\. ( GIF|PNG|JPE?G) $/i);
  },

The suffix of the image type of course contains GIF by default, I just want to illustrate that the code has been adjusted, please note!

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.

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.