Bootstrap FileInput realizes picture uploading function

  • 2021-10-25 05:54:39
  • OfStack

In this paper, we share the specific code of Bootstrap FileInput to realize the picture uploading function for your reference. The specific contents are 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">// Gets the path of the uploaded picture, $("#filesInput").val() Can't get it, use the hidden input To get 
 </div>
</div>

Introducing 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();// Definition 1 Global variables to accept file names 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, // Whether to show preview 
 showCaption: false,// Whether to display the title 
 browseClass: "btn btn-primary", // Button style 
 dropZoneEnabled: false,// Display drag area 
 maxFileCount: 5, // Indicates the maximum number of files allowed to upload 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 Echo Picture Path 
 initialPreviewConfig: picStrConfig // In the configuration preview 1 Some parameters 
 
}).on("fileuploaded", function (event, data, previewId, index) {
 var response = data.response;
 var filePath = data.response.filePath; // File name returned after successful file upload, can return 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 picture 
 
 
}).on('filedeleted',function (event, data, previewId, index) {// Action after deleting the original picture 
 var resources = $("#resources").val();
 var respone = previewId.responseJSON;
 if(respone.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 a 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 flow 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 suffix of the file * */
  String filename = multipartFile.getOriginalFilename();
 
  InputStream inputStream;
  String path = "";
  String fileMd5 = "";
  try {
   /**  Upload files 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 Upper  **/
   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 succeeded ");
  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 picture path in the database first   Then delete the source file of the picture store. **/
  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 to delete the original file? Unrecoverable after deletion ",function () { // Initialize the echoed picture and pop up a prompt box to confirm when it is deleted. 
  if (self.ajaxAborted instanceof Promise) {
   self.ajaxAborted.then(function (result) {
    if (!result) {
     $.ajax(settings);
    }
   });
  } else {
   if (!self.ajaxAborted) {
    $.ajax(settings);
   }
  }
  })
 });
});

Related articles: