The fileinput multiimage upload and editing function in Bootstrap,

Source: Internet
Author: User

The fileinput multiimage upload and editing function in Bootstrap,

If you are not clear about the Bootstrap-fileinput configuration, visit the official website http://plugins.krajee.com/file-input.

Logic Description: first obtain the data presentation from the background and then edit it.

Let's talk about the code.

1. Some Page code:

<Div class = "form-group"> <label for = "inputEmail3" class = "col-xs-3 control-label"> Project LOGO </label> <div class = "col-xs-7"> <input id = "testlogo" type = "file" name = "icoFile" class = "file-loading"/> <input type = "text" name = "htestlogo" id = ""htestlogo" onchange = "addFile (this) "> </div>

Note: onchange () is a business requirement. After the upload is complete, an add event is automatically executed. This method can be removed.

2. How to get the initialization data:

// Initialize and obtain the original file $ (function () {$. ajax ({type: "post", url: "/eim/project/testFileUpload. do ", dataType:" json ", success: function (data) {layer. msg ('Operation successful! '); ShowPhotos (data) ;}, error: function (XMLHttpRequest, textStatus, errorThrown) {layer. msg ('Operation failed! ');}});});

Note: Here I return an array of objects: List <MemberUser>, which can be understood as obtaining all the students in a class and displaying their portraits.

3. initialize the bootstrap-fileinput component:

Function showPhotos (djson) {// return the json string to the json object var reData = eval (djson); // preview the json Data Group var preList = new Array (); for (var I = 0; I <reData. length; I ++) {var array_element = reData [I]; // This pointer is used to determine if (array_element.fileIdFile.name.indexOf ("txt")> 0) {// preList [I] = "<div class = 'file-preview-other-framework'> <div class = 'file-preview-other '> <span class = 'file-icon-4x '> <I class = 'fa Fa-file-text-o text-info'> </I> </span> </div> "} else {// image type preList [I] = " </I>', allowedPreviewTypes: ['image'], previewFileIconSettings: {'docx': '<I class = "fa-file-word-o text-primary"> </I>', 'xlsx ': '<I class = "fa-file-excel-o text-success"> </I>', 'ppt ': '<I class = "fa-file-powerpoint-o text-danger"> </I>', 'pdf ': '<I class = "fa-file-pdf-o text-danger"> </I>', 'zip ': '<I class = "fa-file-archive-o text-muted"> </I>', 'SQL ': '<I class = "fa-file-word-o text-primary"> </I>',}, initialPreviewConfig: preConfigList }). off ('filepreupload '). on ('filepreupload', function () {// alert (data. url );}). on ("fileuploaded", function (event, outData) {// data returned after the file is uploaded successfully. Here, I only save the id var result = outData of the returned file. response. id; // the corresponding input value $ ('# htestlogo '). val (result ). change ();});}

4. save part of the file code in the background java

@ RequestMapping (value = "/uploadFile", method = RequestMethod. POST) @ ResponseBody public Object uploadFile (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// transform to MultipartHttpServletRequest complete multipartRequest = (response) request; // obtain the file and map it to the Map container <String, MultipartFile> fileMap = multipartRequest. getFileMap (); // obtain the path parameter passed by the page folderPath = request. getParameter ("folder"); String rootPath = BaseConfig. uploadPath; String filePath = rootPath + folderPath + "/"; // upload the file and return the map container. map stores the file information FileModel fileModel = UploadifyUtils. uploadFiles (filePath, fileMap); boolean flag = service. add (fileModel); if (flag) {String result = fileModel. getId () + ";" + fileModel. getFilePath () + ";" + fileModel. getName () + ";" + fileModel. getFilePath (); Map map = new HashMap <> (); map. put ("id", fileModel. getId (); // the ID of the returned file. // response. getWriter (). write (map); return map;} return null ;}

Note: The code in this section is used to obtain part of the information of the uploaded file, such as the file name and upload path. The file information is saved to the table and the corresponding object is FileModel.

5. Refresh the component after the upload is complete.

Final display effect:

Note: here, the pointer determines the txt file type, and the remaining doc and ppt files have corresponding display icons. You only need to add corresponding styles in the judgment.

Attachment: Upload/download the file code based on the path:

/*** File Download ** @ param savePath * save directory * @ param name * the original name of the file * @ param file * contains the suffix * @ param request * @ param response * @ return */public static String down (String savePath, string name, String fileName, HttpServletRequest request, HttpServletResponse response) {try {String path = savePath + "/" + name; File file = new File (path); if (! File. exists () {// request does not exist. setAttribute ("name", fileName); return "download_error"; // return that the downloaded file does not exist} response. setContentType ("application/octet-stream"); // set response Header String userAgent = request according to different browsers. getHeader ("User-Agent "). toLowerCase (); if (userAgent. indexOf ("msie ")! =-1) {// IE browser // System. out. println ("IE browser"); response. addHeader ("Content-Disposition", "attachment; filename =" + URLEncoder. encode (name, "UTF-8");} else {response. addHeader ("Content-Disposition", "attachment; filename =" + new String (name. getBytes ("UTF-8"), "ISO8859-1");} response. addHeader ("Content-Length", "" + file. length (); // download the object in the form of a stream. InputStream Fi = new BufferedInputStream (new FileI NputStream (path); byte [] buffer = new byte [FCM. available ()]; FCM. read (buffer); FCM. close (); // response. setContentType ("image/*"); // set the returned file type OutputStream toClient = response. getOutputStream (); OutputStream bos = new BufferedOutputStream (toClient); // BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (bos); bos. write (buffer); // bw. close (); bos. close (); toClient. close (); return null ;} Catch (Exception e) {e. printStackTrace (); // response. reset (); return "exception"; // return the Exception page} finally {/* if (toClient! = Null) {try {toClient. close ();} catch (IOException e) {e. printStackTrace ();}}*/}}

Appendix:

UploadifyUtils. uploadFiles code

Public static FileModel uploadFiles (String savePath, Map <String, MultipartFile> fiLeMap) {// upload a file // The attachment model object FileModel fm = new FileModel (); try {File file = new File (savePath); // you can check whether a folder exists. if not, create the folder makeDir (file); if (fiLeMap! = Null) {for (Map. Entry <String, MultipartFile> entity: fiLeMap. entrySet () {MultipartFile f = entity. getValue (); if (f! = Null &&! F. isEmpty () {String uuid = UploadifyUtils. getUUID (); // uuid is used as the file name for saving String ext = UploadifyUtils. getFileExt (f. getOriginalFilename (); // obtain the File suffix // save the File newFile = new File (savePath + "/" + uuid + ". "+ ext); f. transferTo (newFile); fm. setFileName (f. getOriginalFilename (); fm. setName (uuid + ". "+ ext); fm. setFilePath (savePath); // save path fm. setExt (ext); fm. setSize (f. getSize () ;}}return fm;} catch (Exception e) {log. error (e); return null ;}}

The above section describes how to upload and edit fileinput multi-image files in Bootstrap. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.