1. 程式人生 > >Spring Boot使用FastDFS結合Dropzone.js Bootstrap上傳圖片

Spring Boot使用FastDFS結合Dropzone.js Bootstrap上傳圖片

緒論

dropzone.js是一個非常強大的圖片上傳外掛,而如今bootstrap的扁平化風格又如些的流行,當然也dropzone.js也有bootstrap風格的主題。本文主要講如何在spring boot中使用dropzone.js實現圖片上傳功能。先看看效果:
這裡寫圖片描述

配置Spring Boot對上傳圖片支援

在spring boot的啟動類中新增bean

//顯示宣告CommonsMultipartResolver為mutipartResolver
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver
() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setDefaultEncoding("UTF-8"); resolver.setResolveLazily(true);//resolveLazily屬性啟用是為了推遲檔案解析,以在在UploadAction中捕獲檔案大小異常 resolver.setMaxInMemorySize(40960); resolver.setMaxUploadSize(50 * 1024
* 1024);//上傳檔案大小 50M 50*1024*1024 return resolver; }

上面的bean是配置multipartResolver,如果使用Spring MVC請新增:

<!-- 圖片上傳 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

頁面程式碼css

/*圖片上傳樣式*/
#actions {
  margin: 2em 0;
}
/* Mimic table appearance */
div.table { display: table; } div.table .file-row { display: table-row; } div.table .file-row > div { display: table-cell; vertical-align: top; border-top: 1px solid #ddd; padding: 8px; } div.table .file-row:nth-child(odd) { background: #f9f9f9; } /* The total progress gets shown by event listeners */ #total-progress { opacity: 0; transition: opacity 0.3s linear; } /* Hide the progress bar when finished */ #previews .file-row.dz-success .progress { opacity: 0; transition: opacity 0.3s linear; } /* Hide the delete button initially */ #previews .file-row .delete { display: none; } /* Hide the start and cancel buttons and show the delete button */ #previews .file-row.dz-success .start, #previews .file-row.dz-success .cancel { display: none; } #previews .file-row.dz-success .delete { display: block; }

頁面html

                            <!-- 上傳圖片上面控制按鈕 開始 -->
                            <div id="actions" class="row">

                              <div class="col-lg-7">
                                <!-- The fileinput-button span is used to style the file input field as button -->
                                <span class="btn btn-success fileinput-button">
                                    <i class="glyphicon glyphicon-plus"></i>
                                    <span>新增圖片</span>
                                </span>
                                <button type="submit" class="btn btn-primary start">
                                    <i class="glyphicon glyphicon-upload"></i>
                                    <span>開始上傳</span>
                                </button>
                                <button type="reset" class="btn btn-warning cancel">
                                    <i class="glyphicon glyphicon-ban-circle"></i>
                                    <span>取消上傳</span>
                                </button>
                              </div>

                              <div class="col-lg-5">
                                <!-- The global file processing state -->
                                <span class="fileupload-process">
                                  <div id="total-progress" class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
                                    <div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
                                  </div>
                                </span>
                              </div>

                            </div>
                            <!-- 上傳圖片上面控制按鈕 結束 -->

                            <!-- 上傳圖片表格 開始  -->
                            <div class="table table-striped files" id="previews">

                              <div id="template" class="file-row">
                                <!-- This is used as the file preview template -->
                                <div>
                                    <span class="preview"><img data-dz-thumbnail /></span>
                                </div>
                                <div>
                                    <p class="name" data-dz-name></p>
                                    <strong class="error text-danger" data-dz-errormessage></strong>
                                </div>
                                <div>
                                    <p class="size" data-dz-size></p>
                                    <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
                                      <div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
                                    </div>
                                </div>
                                <div>
                                  <button class="btn btn-primary start">
                                      <i class="glyphicon glyphicon-upload"></i>
                                      <span>開始</span>
                                  </button>
                                  <button data-dz-remove class="btn btn-warning cancel">
                                      <i class="glyphicon glyphicon-ban-circle"></i>
                                      <span>取消</span>
                                  </button>
                                  <button data-dz-remove class="btn btn-danger delete">
                                    <i class="glyphicon glyphicon-trash"></i>
                                    <span>刪除</span>
                                  </button>
                                </div>
                              </div>

                            </div>
                            <!-- 上傳圖片表格 結束  -->

頁面核心js

/******************商品圖片上傳START********************/
        // Get the template HTML and remove it from the doument
        var previewNode = document.querySelector("#template");
        previewNode.id = "";
        var previewTemplate = previewNode.parentNode.innerHTML;
        previewNode.parentNode.removeChild(previewNode);
        //index of urls
        var index = 0;
        var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
          url: "${request.contextPath}/upload/uploadDropZonePics.do", // Set the url
          thumbnailWidth: 80,
          thumbnailHeight: 80,
          uploadMultiple: true,
          parallelUploads: 20,
          maxFiles: 5,
          //dictMaxFilesExceeded: "最多隻能上傳5張圖片!",
          previewTemplate: previewTemplate,
          autoQueue: false, // Make sure the files aren't queued until manually added
          previewsContainer: "#previews", // Define the container to display the previews
          clickable: ".fileinput-button", // Define the element that should be used as click trigger to select files.
          init: function() {
            this.on("success", function(file, response) {
              // Handle the responseText here. For example, add the text to the preview element:
              var input = document.createElement("input"); 
              input.type = "hidden" ;
              input.name = "images" ;
              input.value = response.urls[index];
              file.previewTemplate.appendChild(input);
              index ++;
            });
          }
        });

        myDropzone.on("addedfile", function(file) {
            // Hookup the start button
            file.previewElement.querySelector(".start").onclick = function() { myDropzone.enqueueFile(file); };
        });

        // Update the total progress bar
        myDropzone.on("totaluploadprogress", function(progress) {
            document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
        });

        myDropzone.on("sending", function(file) {
            // Show the total progress bar when upload starts
            document.querySelector("#total-progress").style.opacity = "1";
            // And disable the start button
            file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
        });

        // Hide the total progress bar when nothing's uploading anymore
        myDropzone.on("queuecomplete", function(progress) {
            document.querySelector("#total-progress").style.opacity = "0";
        });
        myDropzone.on("successmultiple", function(files, response) {
            //Initializing index when success
            index = 0;
        });
        myDropzone.on("maxfilesexceeded", function(file) { 
            this.removeFile(file);
            reminder("最多隻能上傳<font color='red'>5</font>張圖片!")
        });
        // Setup the buttons for all transfers
        // The "add files" button doesn't need to be setup because the config
        // `clickable` has already been specified.
        document.querySelector("#actions .start").onclick = function() {
            myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
        };
        document.querySelector("#actions .cancel").onclick = function() {
            myDropzone.removeAllFiles(true);
        };
        /******************商品圖片上傳END********************/

url引數對應的是fastDFS圖片上傳的地址,必填。
thumbnailWidth代表的是縮圖的寬度畫素。
thumbnailHeight代表的是縮圖的高度畫素。
uploadMultiple是否允許一次上傳多張。
parallelUploads並行上傳,一次最多允許數。
maxFiles最多上傳檔案數。
previewTemplate預覽模板。

在上面js中,我新建了一個hidden的input,用來儲存所有返回的圖片url:

var input = document.createElement("input"); 
              input.type = "hidden" ;
              input.name = "images" ;
              input.value = response.urls[index];
              file.previewTemplate.appendChild(input);

後臺實現

/**
     * dropzone.js批量上傳圖片
     * 
     * @param pic
     */
    @RequestMapping(value = ("/upload/uploadDropZonePics.do"))
    @ResponseBody
    public UploadResponse uploadDropZonePic(MultipartHttpServletRequest request) {
        log.info("uploadPic uploadDropZonePic start.");
        UploadResponse resp = new UploadResponse();
        try {
            Iterator<String> itr = request.getFileNames();
            List<String> urls = new ArrayList<>();
            while (itr.hasNext()) {
                String uploadedFile = itr.next();
                MultipartFile file = request.getFile(uploadedFile);
                String filename = file.getOriginalFilename();
                byte[] bytes = file.getBytes();

                //上傳圖片
                UploadFileVo vo = new UploadFileVo();
                vo.setPic(bytes);
                vo.setName(filename);
                vo.setSize(file.getSize());
                String path = uploadService.uploadPic(vo);
                //圖片url
                String url = Constants.IMG_URL + path;
                urls.add(url);
            }
            resp.setIsSuccess(true);
            resp.setUrls(urls);
        } catch (IOException e) {
            log.error("uploadDropZonePic io error:{}", e.getMessage(), e);
            resp.setErrorMsg("上傳圖片失敗:" + e.getMessage());
            resp.setError(1);
            log.error("uploadFck error:{}", e.getMessage(), e);
        } catch (BizException e) {
            log.error("uploadDropZonePic biz error:{}", e.getMessage(), e);
            resp.setErrorMsg("上傳圖片失敗:" + e.getMessage());
            resp.setError(1);
            log.error("uploadFck error:{}", e.getMessage(), e);
        } catch (Exception e) {
            log.error("uploadDropZonePic error:{}", e.getMessage(), e);
            resp.setErrorMsg("上傳圖片失敗:" + e.getMessage());
            resp.setError(1);
            log.error("uploadFck error:{}", e.getMessage(), e);
        }
        log.info("uploadDropZonePic end.");
        return resp;
    }