bootstrap fileinput插件 實現表單數據和圖片異步上傳的方法

js爲:javascript

<script type="text/javascript" src="${APP_PATH}/static/bootstrap-fileinput/fileinput.min.js"></script>           
<script type="text/javascript" src="${APP_PATH}/static/bootstrap-fileinput/locales/zh.js"></script>          
<link href="${APP_PATH}/static/bootstrap-fileinput/fileinput.min.css" rel="stylesheet" />

html:css

<form action="news/addnews.action"  method="POST"  id="addnew_form">
                    <input type="text" name="head" >
                     <input type="file" name="newpic"  class="myfile"/> 
                    <input type="text" name="body">
                    <button type="submit" >推送</button>
            </form>

js寫法:html

$(".myfile").fileinput({
      uploadUrl:"${APP_PATH}/news/uploadFile", //接受請求地址
      uploadAsync : true, //默認異步上傳
      showUpload : false, //是否顯示上傳按鈕,跟隨文本框的那個
      showRemove : false, //顯示移除按鈕,跟隨文本框的那個
      showCaption : true,//是否顯示標題,就是那個文本框
      showPreview : true, //是否顯示預覽,不寫默認爲true
      dropZoneEnabled : false,//是否顯示拖拽區域,默認不寫爲true,可是會佔用很大區域
      //minImageWidth: 50, //圖片的最小寬度
      //minImageHeight: 50,//圖片的最小高度
      //maxImageWidth: 1000,//圖片的最大寬度
      //maxImageHeight: 1000,//圖片的最大高度
      //maxFileSize: 0,//單位爲kb,若是爲0表示不限制文件大小
      //minFileCount: 0,
      maxFileCount : 1, //表示容許同時上傳的最大文件個數
      enctype : 'multipart/form-data',
      validateInitialCount : true,
      previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
      msgFilesTooMany : "選擇上傳的文件數量({n}) 超過容許的最大數值{m}!",
      allowedFileTypes : [ 'image' ],//配置容許文件上傳的類型
      allowedPreviewTypes : [ 'image' ],//配置全部的被預覽文件類型
      allowedPreviewMimeTypes : [ 'jpg', 'png', 'gif' ],//控制被預覽的全部mime類型
      language : 'zh'
  })
  //異步上傳返回結果處理
  $('.myfile').on('fileerror', function(event, data, msg) {
      console.log("fileerror");
      console.log(data);
  });
  //異步上傳返回結果處理
  $(".myfile").on("fileuploaded", function(event, data, previewId, index) {
      console.log("fileuploaded");
      var ref = $(this).attr("data-ref");
      $("input[name='" + ref + "']").val(data.response.url);

  });

  //上傳前
  $('.myfile').on('filepreupload', function(event, data, previewId, index) {
      console.log("filepreupload");
  });
@RequestMapping("news/uploadFile")
    public String uploadFile(MultipartFile newpic)
            throws IllegalStateException, IOException {
             // 原始圖片名稱
        String oldFileName = newpic.getOriginalFilename(); // 獲取上傳文件的原名
            // 存儲路徑
        String saveFilePath = "D://新建文件夾 (4)//house//src//main//webapp//housepic";
            // 新的圖片名稱
            String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
            // 新圖片
            File newFile = new File(saveFilePath + "\\" + newFileName);
            // 將內存中的數據寫入磁盤
            newpic.transferTo(newFile);
            // 將路徑名存入全局變量mynewpic
            mynewpic = "./housepic/"+newFileName;
    }