Bootstrap FileInput implements image upload function

Bootstrap FileInput implements image upload function

This article example shares the specific code of Bootstrap FileInput to implement the image upload function for your reference. The specific content is as follows

HTML code:

<div class="form-group">
 <label class="col-sm-2 control-label">Picture</label>
 <div class="col-sm-8">
  <input id="filesInput" type="file" multiple data-browse-on-zone-click="true" class="file-loading" accept="image/*" />
  <input id="resources" name="resources" th:value="${record.picUrls}" type="hidden">//Get the uploaded image path, $("#filesInput").val() cannot get it, use hidden input to get it</div>
</div>

Import js and css files

<link href="/ajax/libs/bootstrap-fileinput/fileinput.css" rel="stylesheet" type="text/css"/>
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<script th:src="@{/ajax/libs/bootstrap-fileinput/fileinput.js}"></script>

js code:

var List = new Array(); //Define a global variable to accept the file name and id
$(function () {
 var picStr = [
http:...,
http:....
];
var picStrConfig = [
{caption: "11111", width: "120px", fileid: "123456", url: "deleteData", type: "image", key: "1"},
........
];
$('#filesInput').fileinput({
 theme: 'fas',
 language: 'zh',
 uploadUrl: ctx + 'bike/record/uploadData',
 uploadAsync: true, //Default asynchronous upload showUpload: true, //Whether to display the upload button overwriteInitial: false,
 showRemove : false, //Show the remove button// showPreview : true, //Show preview or not showCaption: false, //Show title or not browseClass: "btn btn-primary", //Button style dropZoneEnabled: false, //Show the drag zone or not maxFileCount: 5, //Indicates the maximum number of files that can be uploaded at the same time enctype: 'multipart/form-data',
 validateInitialCount:true,
 layoutTemplates: {actionUpload: ''},
 maxFilesNum: 5,
 fileType: "any",
 allowedPreviewTypes: ['image'],
 previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
 initialPreviewAsData: true,
 initialPreview: picStr, //Initialize the echo image path initialPreviewConfig: picStrConfig //Configure some parameters in the preview}).on("fileuploaded", function (event, data, previewId, index) {
 var response = data.response;
 var filePath = data.response.filePath; //The file name returned after the file is successfully uploaded. You can return a custom file name List.push({ FileName: filePath, KeyID: previewId })
 // alert(response.filePath);
 // $("#fileMd5").val(response.fileMd5);
 // $("#version").val(response.newVersionName);
 var resources = $('#resources').val();
 if (!resources){
  $("#resources").val(response.filePath);
 }else{
  $("#resources").val(resources+"^_^"+response.filePath);
 }
 
 
}).on('filepredelete', function(event, data, previewId, index) { //Trigger action before deleting the original image}).on('filedeleted',function (event, data, previewId, index) {//Action after deleting the original imagevar resources = $("#resources").val();
 var response = previewId.responseJSON;
 if(response.code == 0){
  var deleteName = "/"+data;
  if(resources.indexOf("^_^"+deleteName)>-1){
   $("#resources").val("^_^"+resources.replace(deleteName,""));
   resources = $("#resources").val();
  }
  if(resources.indexOf(deleteName+"^_^")>-1){
   $("#resources").val(resources.replace(deleteName+"^_^",""));
   resources = $("#resources").val();
  }
  if (resources.indexOf(deleteName)>-1){
   $("#resources").val(resources.replace(deleteName,""));
   resources = $("#resources").val();
  }
 }
}).on('filepreupload', function(event, data, previewId, index) {
 var form = data.form, files = data.files, extra = data.extra,
  response = data.response, reader = data.reader;
}).on("filesuccessremove", function (event, data, previewId, index) {
 var resources = $("#resources").val();
 for (var i = 0; i < List.length; i++) {
  if (List[i].KeyID == data) {
   if(resources.indexOf("^_^"+List[i].FileName)>-1){
    $("#resources").val("^_^"+resources.replace(List[i].FileName,""));
    resources = $("#resources").val();
   }
   if(resources.indexOf(List[i].FileName+"^_^")>-1){
    $("#resources").val(resources.replace(List[i].FileName+"^_^",""));
    resources = $("#resources").val();
   }
   if(resources.indexOf(List[i].FileName)>-1){
    $("#resources").val(resources.replace(List[i].FileName,""));
    resources = $("#resources").val();
   }
   List[i].KeyID = "1"
  }
 }
});
})

Java code:

/**
  * Upload file */
 @RequestMapping("/uploadData")
 @ResponseBody
 public Map<String, Object> uploadData(HttpServletRequest request, HttpServletResponse response) throws Exception{
  request.setCharacterEncoding("UTF-8");
  Map<String, Object> json = new HashMap<String, Object>();
  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 
  /** File stream of page control* */
  MultipartFile multipartFile = null;
  Map map =multipartRequest.getFileMap();
  for (Iterator i = map.keySet().iterator(); i.hasNext();) {
   Object obj = i.next();
   multipartFile=(MultipartFile) map.get(obj);
 
  }
  /** Get the file suffix * */
  String filename = multipartFile.getOriginalFilename();
 
  InputStream inputStream;
  String path = "";
  String fileMd5 = "";
  try {
   /** Upload the file to the repository **/
   inputStream = multipartFile.getInputStream();
   File tmpFile = File.createTempFile(filename,
   filename.substring(filename.lastIndexOf(".")));
   fileMd5 = Files.hash(tmpFile, Hashing.md5()).toString();
   FileUtils.copyInputStreamToFile(inputStream, tmpFile);
   /** Upload to MinIO**/
   path = minioFileUtil.uploadCustomize(multipartFile.getInputStream(), filename.substring(filename.lastIndexOf(".")), "",multipartFile.getContentType());
   /** Upload to Alibaba Cloud OSS **/
// path = AliOSSUtils.getInstance().multpartFileUpload(multipartFile,"bike");
   tmpFile.delete();
 
  } catch (Exception e) {
   e.printStackTrace();
   logger.error("Upload failed",e);
   json.put("fileMd5", fileMd5);
   json.put("message", "Upload failed");
   json.put("status", false);
   json.put("filePath", path);
   return json;
  }
  json.put("fileMd5", fileMd5);
  json.put("message", "Upload successful");
  json.put("status", true);
  json.put("filePath", path);
  json.put("key", UUIDGenerator.getUUID());
  return json;
 }
/**
 * Delete file file */
@RequestMapping("/edit/deleteData/{id}")
@ResponseBody
@Transactional(rollbackFor = Exception.class)
public AjaxResult deleteData(@PathVariable("id")String id, HttpServletRequest request) throws Exception{
 String key = request.getParameter("key");
 Record record = recordService.getById(id);
 String picUrls = record.getPicUrls();
 String deleteName = "/" + key;
 if (picUrls.indexOf("^_^" + deleteName) > -1) {
  picUrls = "^_^" + picUrls.replace(deleteName, "");
 }
 if (picUrls.indexOf(deleteName + "^_^") > -1) {
  picUrls = picUrls.replace(deleteName + "^_^", "");
 }
 if (picUrls.indexOf(deleteName) > -1) {
  picUrls = picUrls.replace(deleteName, "");
 }
 record.setPicUrls(picUrls);
 if (recordMapper.updatePicsById(record) == 1) { /** Delete the image path in the database first and then delete the source file where the image is stored. **/
  minioUtil.removeObject(bucketName, key);
  return success(key);
 }
 return error();
}

Modify fileInput source code:

self._handler($el, 'click', function () {
  if (!self._validateMinCount()) {
   return false;
  }
  self.ajaxAborted = false;
  self._raise('filebeforedelete', [vKey, extraData]);
  //noinspection JSUnresolvedVariable,JSHint
  $.modal.confirm("Are you sure you want to delete the original file? It cannot be restored after deletion",function () { // Initialize the echoed image and pop up a prompt box to confirm when deleting it.
  if (self.ajaxAborted instanceof Promise) {
   self.ajaxAborted.then(function (result) {
    if (!result) {
     $.ajax(settings);
    }
   });
  } else {
   if (!self.ajaxAborted) {
    $.ajax(settings);
   }
  }
  })
 });
});

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Detailed usage of Bootstrap Fileinput file upload component
  • Detailed explanation of bootstrap fileinput, a JS file upload artifact
  • Detailed explanation of using Bootstrap fileinput file upload preview plugin
  • Fileinput in Bootstrap multiple image upload and editing function
  • Bootstrap's fileinput plugin implements multiple file uploads
  • Bootstrapfileinput realizes automatic file upload
  • Based on bootstrap upload plugin fileinput to realize ajax asynchronous upload function (support multiple file upload preview drag)
  • Detailed explanation of the hands-on practice of bootstrap-fileinput file upload control
  • Bootstrap fileinput uploads a new file and removes it, triggering the server to synchronize the deletion of the configuration
  • BootStrap fileinput.js file upload component example code

<<:  Detailed installation and configuration tutorial of mysql5.7 on CentOS

>>:  Detailed examples of Docker-compose networks

Recommend

CSS new feature contain controls page redrawing and rearrangement issues

Before introducing the new CSS property contain, ...

How to enable remote access permissions in MYSQL

1. Log in to MySQL database mysql -u root -p View...

Installation steps of mysql under linux

1. Download the mysql tar file: https://dev.mysql...

NodeJS realizes image text segmentation

This article shares the specific code of NodeJS t...

SQL function to merge a field together

Recently, I need to query all the fields in a rel...

14 Ways to Create Website Content That Engages Your Visitors

When I surf the Net, I often see web sites filled...

Tutorial on deploying jdk and tomcat on centos7 without interface

1. Install xshell6 2. Create a server connection ...

Summary of Linux nc command

NC's full name is Netcat (Network Knife), and...

Detailed explanation of CSS BEM writing standards

BEM is a component-based approach to web developm...

How to install MySQL 5.7 on Ubuntu and configure the data storage path

1. Install MySQL This article is installed via AP...

The front-end page pop-up mask prohibits page scrolling

A problem that front-end developers often encount...

JavaScript implements long image scrolling effect

This article shares the specific code of JavaScri...