本文实例为大家分享了bootstrap fileinput实现图片上传功能的具体代码,供大家参考,具体内容如下

html代码:

<div class="form-group">
 <label class="col-sm-2 control-label">图片</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">//获取上传的图片路径,$("#filesinput").val()获取不到,用隐藏的input来获取
 </div>
</div>

引入js和css文件

<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代码:

var list = new array();//定义一个全局变量去接受文件名和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, //默认异步上传
 showupload: true, //是否显示上传按钮
 overwriteinitial: false,
 showremove : false, //显示移除按钮
 // showpreview : true, //是否显示预览
 showcaption: false,//是否显示标题
 browseclass: "btn btn-primary", //按钮样式
 dropzoneenabled: false,//是否显示拖拽区域
 maxfilecount: 5, //表示允许同时上传的最大文件个数
 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, //初始化回显图片路径
 initialpreviewconfig: picstrconfig //配置预览中的一些参数
 
}).on("fileuploaded", function (event, data, previewid, index) {
 var response = data.response;
 var filepath = data.response.filepath; //文件上传成功返回的文件名,可返回自定义文件名
 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) { //删除原图片之前的触发动作
 
 
}).on('filedeleted',function (event, data, previewid, index) {//删除原图片之后的动作
 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代码:

/**
  * 上传文件
*/
 @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;
 
  /** 页面控件的文件流* */
  multipartfile multipartfile = null;
  map map =multipartrequest.getfilemap();
  for (iterator i = map.keyset().iterator(); i.hasnext();) {
   object obj = i.next();
   multipartfile=(multipartfile) map.get(obj);
 
  }
  /** 获取文件的后缀* */
  string filename = multipartfile.getoriginalfilename();
 
  inputstream inputstream;
  string path = "";
  string filemd5 = "";
  try {
   /** 文件上传到存储库中 **/
   inputstream = multipartfile.getinputstream();
   file tmpfile = file.createtempfile(filename,
   filename.substring(filename.lastindexof(".")));
   filemd5 = files.hash(tmpfile, hashing.md5()).tostring();
   fileutils.copyinputstreamtofile(inputstream, tmpfile);
   /** 上传到 minio上 **/
   path = miniofileutil.uploadcustomize(multipartfile.getinputstream(), filename.substring(filename.lastindexof(".")), "",multipartfile.getcontenttype());
   /** 上传 到 阿里云oss **/
//   path = aliossutils.getinstance().multpartfileupload(multipartfile,"bike");
   tmpfile.delete();
 
  } catch (exception e) {
   e.printstacktrace();
   logger.error("上传失败",e);
   json.put("filemd5", filemd5);
   json.put("message", "上传失败");
   json.put("status", false);
   json.put("filepath", path);
   return json;
  }
  json.put("filemd5", filemd5);
  json.put("message", "上传成功");
  json.put("status", true);
  json.put("filepath", path);
  json.put("key", uuidgenerator.getuuid());
  return json;
 }
/**
 * 删除文件文件
 */
@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) { /** 先删除数据库中的图片路径 再删除图片存储的源文件。**/
  minioutil.removeobject(bucketname, key);
  return success(key);
 }
 return error();
}

修改 fileinput 源码:

self._handler($el, 'click', function () {
  if (!self._validatemincount()) {
   return false;
  }
  self.ajaxaborted = false;
  self._raise('filebeforedelete', [vkey, extradata]);
  //noinspection jsunresolvedvariable,jshint
  $.modal.confirm("确定删除原文件?删除后不可恢复",function () { //初始化回显的图片在删除时弹出提示框确认。
  if (self.ajaxaborted instanceof promise) {
   self.ajaxaborted.then(function (result) {
    if (!result) {
     $.ajax(settings);
    }
   });
  } else {
   if (!self.ajaxaborted) {
    $.ajax(settings);
   }
  }
  })
 });
});

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。