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

Introduction to 10 Hooks in React

Table of contents What is ReactHook? React curren...

How to configure Nginx load balancing

Table of contents Nginx load balancing configurat...

Comprehensive analysis of MySql master-slave replication mechanism

Table of contents Master-slave replication mechan...

Summary of 7 reasons why Docker is not suitable for deploying databases

Docker has been very popular in the past two year...

Tutorial analysis of quick installation of mysql5.7 based on centos7

one. wget https://dev.mysql.com/get/mysql57-commu...

Vue two-choice tab bar switching new approach

Problem Description When we are working on a proj...

Springboot+Vue-Cropper realizes the effect of avatar cutting and uploading

Use the Vue-Cropper component to upload avatars. ...

Detailed explanation of flex and position compatibility mining notes

Today I had some free time to write a website for...

Ideas and codes for realizing magnifying glass effect in js

This article example shares the specific code of ...

The use and difference between JavaScript pseudo-array and array

Pseudo-arrays and arrays In JavaScript, except fo...

Detailed process of NTP server configuration under Linux

Table of contents 1. Environment Configuration 1....

Vue implements click feedback instructions for water ripple effect

Table of contents Water wave effect Let's see...

What to do after installing Ubuntu 20.04 (beginner's guide)

Ubuntu 20.04 has been released, bringing many new...