1. 程式人生 > >Idea中使用Springboot和webuploader外掛進行檔案上傳

Idea中使用Springboot和webuploader外掛進行檔案上傳

關於使用webuploader進行初步的檔案上傳,做一個筆記。
開發工具: IntelliJ IDEA
使用框架: SpringBoot
前端頁面: FreeMaker

  1. 專案準備
    引入需要的jar包
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId
>
</dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--JDBC的支援依賴--> <!--<dependency>--> <!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-jdbc</artifactId>--> <!--</dependency>--> <!--mysql的連線依賴--> <!--<dependency>--> <!--<groupId>mysql</groupId>--> <!--<artifactId>mysql-connector-java</artifactId>-->
<!--</dependency>--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--熱部署依賴配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!--Google Guava 類庫 包含集合(Collections),快取(Caching),併發程式設計庫(Concurrency) ,常用註解(Common annotations),String操作,I/O操作方面的眾多非常實用的函式。--> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>20.0</version> </dependency> <!--lang3.StringEscapeUtils--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork><!--該配置為熱部署必須的--> </configuration> </plugin> </plugins> </build>
    <link rel="stylesheet" type="text/css" href="/webuploder/css/webuploader.css">
    <script type="text/javascript" src="/webuploder/js/webuploader.js"></script>

3.上傳頁面
完整的demo頁面如下:upload_file.ftl
(由於只是一個demo,所以很簡單,不影響功能)
1). 引入了bootstrap,目的是為了顯示進度條,這個webuploader外掛似乎是不自帶的。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <#--引入bootstrap,用於進度條的展示-->
    <link rel="stylesheet" type="text/css" href="/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="/webuploder/css/webuploader.css">
    <#--調節按鈕的樣式-->
    <style>
        #picker div.webuploader-pick{
            height: 30px;
            padding: 6px 15px;
            margin-top: 3px;
            height: 30px!important;
        }
        #picker {
            float: left;
        }
        #ctlBtn {
            float: left;
            height: 30px;
            margin-left: 15px;
            margin-top: 3px;
            width: 90px;
        }
    </style>
    <title>使用webuploader進行檔案上傳</title>
</head>
<body>
    <h3>使用webuploader進行檔案的上傳</h3>
    <div>
        <div id="uploader" class="wu-example">
            <!--待上傳的檔案列表,用來存放檔案資訊-->
            <div id="thelist" class="uploader-list"></div>
            <div class="btns">
                <div id="picker">選擇檔案</div>
                <button id="ctlBtn" class="btn btn-default">開始上傳</button>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript" src="/jquery/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/bootstrap/js/bootstrap.min.js"></script>
<#--官網下載的js-->
<script type="text/javascript" src="/webuploder/js/webuploader.js"></script>
<#--這是對webuploader的初始化,必要-->
<script type="text/javascript" src="/js/upload_file.js"></script>
</html>

4.初始化webuploder外掛(引用見上)
可以從官網直接拿下來,F12 –> sourse
upload_file.js

// 檔案上傳
jQuery(function() {
    /*對於一些控制元件的初始化*/
    var $ = jQuery,
        //待上傳的檔案列表
        $list = $('#thelist'),
        //開始上傳按鈕
        $btn = $('#ctlBtn'),
        //顯示狀態 上傳成功、上傳失敗。。
        state = 'pending',
        //上傳的方法
        uploader;

    uploader = WebUploader.create({

        // 不壓縮image
        resize: false,

        // 為true 檔案則自動上傳
        auto: false,

        // swf檔案路徑  使用flash才會用到
        // swf: BASE_URL + '/js/Uploader.swf',

        // 檔案接收服務端。就是上傳檔案走的url
        server: '/upload',

        // 選擇檔案的按鈕。可選。
        pick: '#picker',

        // 預設所有都可選,過濾檔案型別參考網址: http://www.cnblogs.com/s.sams/archive/2007/10/10/918817.html
        // 只允許選擇圖片檔案。
        /*accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/!*'
        },*/

        // 只允許選擇Excel檔案。
        accept: {// 只允許選擇Excel檔案格式
            title: 'Excel',
            extensions: 'xls,xlsx',
            mimeTypes: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'  /*限制選擇檔案的型別*/
        }
    });

    // 當有檔案新增進來的時候
    uploader.on( 'fileQueued', function( file ) {
        $list.append( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上傳...</p>' +
        '</div>' );
    });

    // 檔案上傳過程中建立進度條實時顯示。
    // 進度條我引用了bootStrap.css來進行展示,webuploader.css是不帶的
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');

        // 避免重複建立
        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
              '<div class="progress-bar" role="progressbar" style="width: 0%">' +
              '</div>' +
            '</div>').appendTo( $li ).find('.progress-bar');
        }

        $li.find('p.state').text('上傳中');

        $percent.css( 'width', percentage * 100 + '%' );
    });

    // 上傳成功
    uploader.on( 'uploadSuccess', function( file ) {
        $( '#'+file.id ).find('p.state').text('已上傳');
    });

    // 上傳失敗
    uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上傳出錯');
    });

    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
    });

    uploader.on( 'all', function( type ) {
        if ( type === 'startUpload' ) {
            state = 'uploading';
        } else if ( type === 'stopUpload' ) {
            state = 'paused';
        } else if ( type === 'uploadFinished' ) {
            state = 'done';
        }

        if ( state === 'uploading' ) {
            $btn.text('暫停上傳');
        } else {
            $btn.text('開始上傳');
        }
    });

    // 開始上傳 按鈕點選事件 觸發 上傳方法
    // 如果開啟了自動上傳,則不必要
    $btn.on( 'click', function() {
        if ( state === 'uploading' ) {
            uploader.stop();
        } else {
            uploader.upload();
        }
    });
});

5.頁面跳轉

@Controller
public class UploadController {
    @GetMapping("index")
    public String uploadIndex(){
        return "upload_file";
    }
}

6.檔案的接收和上傳

@Controller
public class UploadRestController {
    @PostMapping("/upload")
    public String uploadFile(@RequestPart("file") MultipartFile file) throws IOException {
        // 獲取檔名
        String fileName = file.getOriginalFilename();
        // 獲取專案的路徑 + 拼接得到檔案要儲存的位置
        String filePath = System.getProperties().getProperty("user.dir") + "\\src\\main\\resources\\file\\" + fileName;
        // 建立一個檔案的物件
        File file1 = new File(filePath);
        // 建立父資料夾
        Files.createParentDirs(file1);
        // 把上傳的檔案複製到檔案物件中
        file.transferTo(file1);
        return "upload_file";
    }
}

最終效果:
上傳效果
總結:
1. webuploader樣式比較好看,用起來也比較簡單,樣式在使用的時候可能和官網例子不太一樣,這個可以自己去調。
2. webuploader必須初始化,初始化js:【upload_file.js】,當然這裡的只是檔案的上傳,圖片的以後再補充,或者從官網開發者模式,把原始檔取下來都可以。
3. 進度條我使用的也是官網上的bootstrap
如有需要修正的地方,還請指教。