1. 程式人生 > >java Springboot實現多檔案上傳

java Springboot實現多檔案上傳

前端採用layui框架,講解多檔案上傳的完整實現功能。

前端html重點程式碼如下:

        		<div class="layui-form-item">
			<label class="layui-form-label">上傳檔案</label>
			<div class="layui-input-block">
				<div class="layui-upload">
					<button type="button" class="layui-btn layui-btn-normal" id="testList">選擇多檔案</button>
					<div class="layui-upload-list">
						<table class="layui-table">
							<thead>
							<tr><th>檔名</th>
								<th>大小</th>
								<th>狀態</th>
								<th>操作</th>
							</tr></thead>
							<tbody id="demoList"></tbody>
						</table>
					</div>
					<button type="button" class="layui-btn" id="testListAction">開始上傳</button>
				</div>
			</div>
		</div>

相應的,js程式碼如下所示:

        layui.use('upload', function(){
            var $ = layui.jquery,upload = layui.upload;
            //多檔案列表示例
            var demoListView = $('#demoList')
                ,uploadListIns = upload.render({
                elem: '#testList'
                ,url: '/upload'
                ,accept: 'file'
                ,data:{}   //可放擴充套件資料  key-value
                ,multiple: true
                ,auto: false
                ,bindAction: '#testListAction'
                ,choose: function(obj){
                    var files = this.files = obj.pushFile(); //將每次選擇的檔案追加到檔案佇列
                    //讀取本地檔案
                    obj.preview(function(index, file, result){
                        var tr = $(['<tr id="upload-'+ index +'">'
                            ,'<td>'+ file.name +'</td>'
                            ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
                            ,'<td>等待上傳</td>'
                            ,'<td>'
                            ,'<button class="layui-btn layui-btn-mini demo-reload layui-hide">重傳</button>'
                            ,'<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">刪除</button>'
                            ,'</td>'
                            ,'</tr>'].join(''));

                        //單個重傳
                        tr.find('.demo-reload').on('click', function(){
                            obj.upload(index, file);
                        });

                        //刪除
                        tr.find('.demo-delete').on('click', function(){
                            delete files[index]; //刪除對應的檔案
                            tr.remove();
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免刪除後出現同名檔案不可選
                        });

                        demoListView.append(tr);
                    });
                }
                ,done: function(res, index, upload){
                    if(res.code == 0) //上傳成功
                        var tr = demoListView.find('tr#upload-'+ index)
                            ,tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上傳成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //刪除檔案佇列已經上傳成功的檔案

                } //code為後臺傳回來的資料,具體多少自己定,

                //後臺只能傳回json格式資料,不然會走error函式;

                ,error: function(index, upload){

                }
            })
        });

以上即是前端功能的實現,後端方面,在Service層Impl下建立檔案上傳的函式:

    public String uploadNoticeFile(MultipartFile fileList) {
        try{
            String pathname = filepath;
            String timeMillis = Long.toString(System.currentTimeMillis());//時間戳
            String filename = timeMillis + fileList.getOriginalFilename();
            File dir = new File(pathname);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String filepath = pathname + filename;
            File serverFile = new File(filepath);
            fileList.transferTo(serverFile);

            //存入資料庫
            NoticeFile noticeFile = new NoticeFile();
            noticeFile.setNoFileName(filename);
            noticeFile.setNoFilePath(filepath);
            noticeFile.setNoId(0L);
            noticeFileRepository.save(noticeFile);
            return "1";

        }catch (Exception e) {
            e.printStackTrace();
            return "0";
        }

    }

NoticeFile是我個人在寫專案時建立的類,讀者可根據實際情況自行運用。

然後,在controller層中建立相應的函式:

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> noticeFile(@RequestParam(name = "file") MultipartFile files) {
        String msg = noticeFileService.uploadNoticeFile(files);

        Map map = new HashMap();
        if (msg == "1") {
            map.put("code", "0");
        } else {
            map.put("code", "1");
        }
        return map;
    }
以上,即實現了多檔案上傳的全部功能。