java+springboot+bootstrap-fileInput 文件上傳前后台完整示例


先看效果圖

 

====================================================

引入的js css

<script src="/bootstrap/js/fileinput.min.js"></script>

<link rel="stylesheet" href="/bootstrap/css/fileinput.min.css"/>

================================================

html :

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <link href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.6/css/bootstrap.min.css"
          th:href="@{/webjars/bootstrap/3.3.6/css/bootstrap.min.css}"
          rel="stylesheet" media="screen" />
            <meta charset="utf-8"/>
</head>
<body>
    <div th:fragment="apk-form">
     <form  method="post"   class="box-header with-border" action="" th:object="${apkVersion}" id="dataFrom" enctype="multipart/form-data" >
      <input type="hidden" name ="id" id="id" />
      <input type="hidden" name ="url" id="url" />
      <input type="hidden" name ="fileMd5" id="fileMd5" />
      <input type="hidden" name ="version" id="version" />
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header" style="background: #3c8dbc;">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4 class="modal-title" id="myModalLabel">新增</h4>
        </div>
        <div class="modal-body">
        <div class="form-group">
            <label class="form-label col-3">版本說明:</label>
            <div class="formControls col-5" >
                <textarea name="comment" id="comment" cols="" rows="" class="textarea" style="width: 400px"  placeholder="說點什么...100個字符以內" dragonfly="true" ></textarea>
                <p class="textarea-numberbar"><em class="textarea-length">0</em>/100</p>
            </div>
            <div class="col-4"> </div>
        </div>
        <div class="form-group">
        <label class="control-label">上傳版本:</label>
        <input type="file" name="uploadfile" id="uploadfile" multiple="multiple" class="file-loading" />
        </div>
        
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>關閉</button>
              <input class="btn btn-primary radius" type="button" onclick="save()" value="&nbsp;&nbsp;提交&nbsp;&nbsp;"/>
        </div>
      </div>
    </div>
   
  </div>
 </form>
    </div>
</body>
</html>

 

===============================

<!-- page script -->
<script>function btn_add(){
      $("#myModalLabel").text("添加版本");
       $('#myModal').modal();
     
}
$("#uploadfile").fileinput({
    language: 'zh', //設置語言
    uploadUrl: "/apk_upload", //上傳的地址
    allowedFileExtensions: ['apk'],//接收的文件后綴
    uploadAsync: true, //默認異步上傳
    showUpload: true, //是否顯示上傳按鈕
    
    showRemove : true, //顯示移除按鈕
    showPreview : true, //是否顯示預覽
    showCaption: false,//是否顯示標題
    browseClass: "btn btn-primary", //按鈕樣式     
    dropZoneEnabled: false,//是否顯示拖拽區域
    maxFileCount: 1, //表示允許同時上傳的最大文件個數
    enctype: 'multipart/form-data',
    validateInitialCount:true
});
//異步上傳返回結果處理
$("#uploadfile").on("fileuploaded", function (event, data, previewId, index) {
        var response = data.response;
        alert(response.filePath);
        $("#fileMd5").val(response.fileMd5);
        $("#version").val(response.newVersionName);
        $("#url").val(response.filePath);
       
    });
//上傳前

$('#uploadfile').on('filepreupload', function(event, data, previewId, index) {
   var form = data.form, files = data.files, extra = data.extra,
    response = data.response, reader = data.reader;
});
</script>

========================js  html 網上例子很多很多 , 但是網上找后台接收參數的例子很少,一下是Java 后端代碼:

 

@ResponseBody
    @RequestMapping(value = "/apk_upload" ,method = RequestMethod.POST)
    public Map<String, Object> uploadApkFile(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 newVersionName = "";
        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);
            // 上傳UpYun后返回的path
            String versionGbk = AnalysisApk.unZip(tmpFile.getPath(), "")[0];
            byte[] versionNam = versionGbk.getBytes("iso8859-1");// 這里寫轉換前的編碼方式
            newVersionName = new String(versionNam, "utf-8");// 這里寫轉換后的編碼方式
            path = UpyunUtils.uploadApk(tmpFile,
                    multipartFile.getOriginalFilename(), true, newVersionName);
            System.err.println(path);
            tmpFile.delete();

        } catch (Exception e) {
            e.printStackTrace();
        }
        json.put("newVersionName", newVersionName);
        json.put("fileMd5", fileMd5);
        json.put("message", "應用上傳成功");
        json.put("status", true);
        json.put("filePath", path);
        return json;
    }

======================

我的難點在   怎么接收后台file

 

      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;


其實都存在request 里面。
在方法里面不僅要聲明request 還有聲明response , 上傳之后的文件路徑 回調使用:

//異步上傳返回結果處理
$("#uploadfile").on("fileuploaded", function (event, data, previewId, index) {
        var response = data.response;
        $("#fileMd5").val(response.fileMd5);
        $("#version").val(response.newVersionName);
        $("#url").val(response.filePath);
       
    });








 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM