It is best to use the Bootstrap fileinput. js File Upload Component and the bootstrap Upload Component.

Source: Internet
Author: User

It is best to use the Bootstrap fileinput. js File Upload Component and the bootstrap Upload Component.

This article describes how to use bootstrap fileinput. js (the best File Upload Component) to display and upload images, including saving springMVC backend files.

I. demo

II. 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, which is an official document.

3. Page

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

1. type = file and class = projectfile, specifying it as the input file type.
2. name specifies the key to be obtained in the background.
3. value specifies the image path during display.

4. executed during page loading

Projectfileoptions: {showUpload: false, showRemove: false, language: 'zh ', allowedPreviewTypes: ['image'], allowedFileExtensions: ['jpg', 'png ', 'gif'], maxFileSize: 2000,}, // File Upload box $ ('input [class = projectfile] '). each (function () {var imageurl = $ (this ). attr ("value"); if (imageurl) {var op = $. extend ({initialPreview: [// preview image Settings "

1. Get the corresponding input file through jquery, and then execute the fileinput method.
2. showUpload: Set whether the upload button exists.
3. Specify Chinese language
4. I don't know why allowedFileTypes and allowedFileExtensions didn't work?
5. maxFileSize specifies the size of the uploaded file

5. Submit form with file through ajax

Let's first look at the form layout with file.

<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. image} "/> <p class =" help-block "> supports jpg, jpeg, png, and gif formats, the size cannot exceed 2.0 MB </p> </div> <div class = "form-group text-center"> <div class = "col-md-10 col-md-offset-1"> <button type = "submit" class = "btn-primary btn-lg"> Save </button> </div> </form>

1.Enctype = "multipart/form-data.
2.Onsubmit = "return iframeCallback (this, pageAjaxDone )"Method: submit the form (iframeCallback) through ajax, and call the callback function (pageAjaxDone) after the upload is successful to perform the next operation.

For more information about iframeCallback, see the data submission of the form in which summernote is located.

Next we will 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]; // The YUNM message is displayed. debug (msg); if (YUNM. callbackType. confirmTimeoutForward = json. callbackType) {$. showSuccessTimeout (msg, function () {window. location = json. forwardUrl ;});}}}

The main function is to use the ajaxDone method to process the error messages sent from the server. If the server operation is successful, a prompt message is displayed, and then jump to the corresponding url.

Vi. springMVC save images

Please refer to the back-end springMVC file to save

Ps:The above blog left a small question and never studied it until a very good friend gave me the following reminder:

Ihchenchen posted a [reply] allowedFileTypes and allowedFileExtensions at yesterday. I know why it is ineffective because the fileinput () method is called twice, once in fileinput. the last few lines in js are also written by yourself (this ). fileinput (). In fileinput. js, The allowedFileTypes and allowedFileExtensions values are not set. There are two ways to change: 1. comment out the last few lines in fileinput. js. 2. Use the "data-" method instead of (this). fileinput ().

I am very grateful for the kindly reminder of ihchenchen. Although his explanations have not solved my questions, I like this interactive technical exchange. I have written many blogs before, basically, this kind of good faith and effective answer rarely happens. This reminds me of Chinese programmers and foreign programmers. The story in it is shocking, and it is a bit embarrassing. Then how can we achieve "Ask questions, get answers, no distractions ." It seems very precious, and "ihchenchen" is full of this spirit!

6. Unlock allowedFileTypes and allowedFileExtensions

I was confused about why bootstrap fileinput had no effect after setting these two attributes. It was my own misunderstanding. Now, after some painstaking understanding, I suddenly realized it!

① AllowedFileTypes

AllowedFileTypes
Array the list of allowed file types for upload. this by default is set to null which means the plugin supports all file types for upload. if an invalid file type is found, then a validation error message as set in msgInvalidFileType will be raised. the following types as set in fileTypeSettings are available for setup.

['Image', 'html', 'text', 'video', 'audio', 'flash', 'object']

Starting with "allowedFileTypes", this attribute tells us the file selection type, so we can easily think of this picture:

In other words, we hope that "all files" are not "all files", but "image" and so on. Obviously, this logic is correct, but it is not suitable for bootstrap fileinput!

In this case, it is easy to think that "allowedFileTypes" does not work!

But please refer:

Hey, it turns out to be a type check after you select the file!

② Working Principle of allowedFileTypes

 $(this).fileinput({ showUpload : false, showRemove : false, language : 'zh', allowedPreviewTypes: ['image'], allowedFileTypes: ['image'], allowedFileExtensions: ['jpg', 'png'], maxFileSize : 2000, });

Through the fileinput method, we load a bootstrap fileinput component. How does one implement allowedFileTypes internally?

By searching the keyword "allowedFileTypes" 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), fileCount = 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 = fileTypes[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 find that the check for the file type occurs on the checkFile method. So what exactly does the checkFile method do?

 defaultFileTypeSettings = {  image: function (vType, vName) {   return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(png|jpe?g)$/i);  },  ...

The above is the content of checkFile.

  • That is to say, when allowedFileTypes: ['image'] is specified, the image type is checked.
  • Obviously, the txt file we selected does not belong to the image type, so it will not match. The above interface will appear.
  • At the same time, this method tells us that if allowedFileTypes: ['image'] is not specified, only allowedFileExtensions: ['jpg ', 'png'] is specified, the vName will be executed. match (/\. (png | jpe? G) $/I), that is, the check of the file suffix type. This is critical and lays the foundation for the next introduction of "allowedFileExtensions.

③ When does allowedFileExtensions take effect?

In the previous section, we discussed "allowedFileTypes" and "allowedFileExtensions" in the example. How can we check the suffix?

 $(this).fileinput({    showUpload : false,    showRemove : false,    language : 'zh',    allowedPreviewTypes: ['image'],    allowedFileExtensions: ['jpg', 'png'],    maxFileSize : 2000,   });

The specified attributes of the fileinput component are as follows: "allowedFileTypes" is absent, and the allowed suffix type is "['jpg ', 'png']". That is, if you select a gif image, an error message is displayed.

The error is expected, so pay special attention to the following:

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 includes gif by default. For example, the Code has been adjusted. Please note!

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.