If you don’t know the configuration of Bootstrap-fileinput, you can check the official website: http://plugins.krajee.com/file-input.
Logical description: First get the data display from the background, and then edit it.
Without further ado, just upload the code.
1. Part of the page code:
<div> <label for="inputEmail3">Project LOGO</label> <div> <input id="testlogo" type="file" name="icoFile" /> <input type="text" name="htestlogo" id="htestlogo" onchange="addFile(this)" > </div> </div>
Note: where onchange() is required by my business, and an addition event will be automatically executed after the upload is completed. This method can be removed.
2. Get the initialization data method:
// Initialize to get the original file $(function(){ $.ajax({ type : "post", url : "/eim/project/testFileUpload.do", dataType : "json", success : function(data) { layer.msg('operation succeeds!'); showPhotos(data); }, error: function(XMLHttpRequest, textStatus, errorThrown) { layer.msg('operation failed!'); } }); });Description: Here I return an object array: List<MemberUser>, which can be understood as getting all students in a class and displaying avatars
3. Initialize the bootstrap-fileinput component:
function showPhotos(djson){ //Return the json string to a json object in the background var reData = eval(djson); // Preview the picture json data group var preList = new Array(); for ( var i = 0; i < reData.length; i++) { var array_element = reData[i]; // Here we refer to the judgment for .txt, and add the rest to yourself if(array_element.fileIdFile.name.indexOf("txt")>0){ // Display of non-image types preList[i]= "<div class='file-preview-other-frame'><div class='file-preview-other'><span class='file-icon-4x'><i class='fa fa-file-text-o text-info'></i></span></div></div>" }else{ // Image type preList[i]= "<img src=/"/eim/upload/getIMG.do?savePath="+array_element.fileIdFile.filePath+"&name="+array_element.fileIdFile.name+"/" class=/" file-preview-image/">"; } } var previewJson = preList; // config data corresponding to the json data group of the preview image above var preConfigList = new Array(); for ( var i = 0; i < reData.length; i++) { var array_element = reData[i]; var tjson = {caption: array_element.fileIdFile.fileName, // The displayed file name width: '120px', url: '/eim/project/deleteFile.do', // Delete url key: array_element.id, // Delete is the parameter passed by Ajax to the background extra: {id: 100} }; preConfigList[i] = tjson; } // Query the specific parameters by yourself.fileinput({ uploadUrl: '/eim/upload/uploadFile.do', uploadAsync:true, showCaption: true, showUpload: true,//Whether the upload button is displayed, showRemove: false,//Whether the delete button is displayed, showCaption: true,//Whether the input box is displayed, showPreview:true, showCancel:true, dropZoneEnabled: false, maxFileCount: 10, initialPreviewShowDelete:true, msgFilesTooMany: "Select the number of uploaded files exceeds the maximum allowed value!", initialPreview: previewJson, previewFileIcon: '<i></i>', allowedPreviewTypes: ['image'], previewFileIconSettings: { 'docx': '<i></i>', 'xlsx': '<i></i>', 'pptx': '<i></i>', 'pdf': '<i></i>', 'zip': '<i></i>', 'sql': '<i></i>', }, initialPreviewConfig: preConfigList }).off('filepreupload').on('filepreupload', function() { // alert(data.url); }).on("fileuploaded", function(event, outData) { // The data returned after the file is uploaded successfully, here I only save the id of the returned file var result = outData.response.id; // The corresponding input assignment $('#htestlogo').val(result).change(); }); }4. Backend Java saves part of the file code
@RequestMapping(value="/uploadFile",method=RequestMethod.POST) @ResponseBody public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Convert to MultipartHttpServletRequest MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request; //Get the file into the map container Map<String,MultipartFile> fileMap = multipartRequest.getFileMap(); //Get 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, the map stores 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()); //Return file save ID //response.getWriter().write(map); return map; } return null; }Note: This code obtains part of the information of the uploaded file, such as the file name, the uploaded path, etc., and saves the file information into the table, and the corresponding object is FileModel.
5. Refresh the component after the upload is completed.
Final display effect:
Note: Here we refer to the txt file type judgment. For the rest of the doc and ppt, there are corresponding display icons. You only need to add the corresponding style when determining whether to judge.
Attachment: According to the path past/download file code:
/** * File download* * @param savePath * Save directory* @param name * Original file * The name when saving 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.setAttribute("name", fileName); return "download_error";// Return the download file does not exist} response.setContentType("application/octet-stream"); // Set the response's Header String userAgent = request.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 file in the form of a stream InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); //response.setContentType("image/*"); //set return 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 to the exception page} finally { /* if (toClient != null) { try { toClient.close(); } catch (IOException e) { e.printStackTrace(); } }*/ } }Attached:
UploadifyUtils.uploadFiles Part of the code
public static FileModel uploadFiles(String savePath,Map<String,MultipartFile> fiLeMap){ //Upload the file//Attachment model object FileModel fm=new FileModel(); try { File file = new File(savePath); //Determine whether the folder exists, and if it does not exist, 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 the file name when saving String ext=UploadifyUtils.getFileExt(f.getOriginalFilename());//get file suffix//Save file 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 is the upload and editing of fileinput in Bootstrap introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!