1. 程式人生 > >Layui檔案上傳(java)

Layui檔案上傳(java)

Layui檔案上傳的一些引數,這裡不過多介紹,詳情可看Layui檔案上傳引數設定,這裡主要介紹【springMVC】上傳檔案

spring配置

springmvc.xml加入配置

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1000000000" />
    </bean>

單檔案上傳

html程式碼:

  <div class="layui-upload" style="margin-left: 30px;margin-right: 30px;">
   <div style="margin-top: 171px;float: left;"><label class="layui-form-label">店鋪圖片</label></div>
  <div class="layui-upload-list" style="float: left;">
    <img class="layui-upload-img"
id="demo1" style="width: 200px;height: 200px;margin: 0 10px 10px 0;"> <p id="demoText"></p> <input type="hidden" name="pic" id="pic" value="${store.pic }"> </div> <div style="float: left;margin-top: 171px;"><button type="button" class="layui-btn" id="test1">上傳圖片</button></div
> </div>

js程式碼:

layui.use(['form','layer','table','upload'], function(){
          var table = layui.table
          ,form = layui.form,upload = layui.upload;
           var uploadInst = upload.render({
            elem: '#test1'
            ,url: 'sysstore/uploadImg'
            ,before: function(obj){
              //預讀本地檔案示例,不支援ie8
              obj.preview(function(index, file, result){
                $('#demo1').attr('src', result); //圖片連結(base64)
              });
            }
            ,done: function(res){
              //如果上傳失敗
              if(res.code > 0){//自定義返回失敗
                return layer.msg('上傳失敗');
              }else{
                  $('#pic').val(res.img); 
              }
              //上傳成功
            }
            ,error: function(){
              //演示失敗狀態,並實現重傳
              var demoText = $('#demoText');
              demoText.html('<span style="color: #FF5722;">上傳失敗</span> <a class="layui-btn layui-btn-mini demo-reload">重試</a>');
              demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
              });
            }
          });

})

service之-java程式碼(我返回的是檔案路徑名):

public String uploadImg(MultipartFile file) {
        if (null != file) {
            String myFileName = file.getOriginalFilename();// 檔案原名稱
            String fileName = BasePath.getImgPath("yyyyMMddHHmmss")+
                    Integer.toHexString(new Random().nextInt()) +"."+ myFileName.
                    substring(myFileName.lastIndexOf(".") + 1);  
            String pat=FileProperties.getFilePath()+"/src/main/webapp/";//獲取檔案儲存路徑
            String sqlPath="static/images/upload/storeHead/"+BasePath.getImgPath("yyyyMMdd")+"/"; 

            File fileDir=new File(pat+sqlPath);
            if (!fileDir.exists()) { //如果不存在 則建立     
                 fileDir.mkdirs();    
             } 
            String path=pat+sqlPath+fileName;
            File localFile = new File(path);  
            try {
                file.transferTo(localFile);
                return sqlPath+fileName;
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            System.out.println("檔案為空");
        }
        return null;
    }

鑑於大家對SysFileEntity多有異議這裡補上這個實體類

package com.yun.entity;

import java.io.Serializable;

import org.springframework.format.annotation.DateTimeFormat;

import com.fasterxml.jackson.annotation.JsonFormat;

import lombok.Data;


@Data
public class SysFileEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 檔案id
     */
    private Long fileId;
    /*

     */
    private String orderNum;
    /**
     * 原始檔名
     */
    private String fileName;
    /**         
     * 檔案路徑
     */
    private String fileUrl;
    /**
     * 使用者id
     */
    private Long userId;
    /**
     * 使用者
     */
    private String userName;
    /**
     * 店鋪id
     */
    private Long storeId;
    /**
     * 店鋪名稱
     */
    private String storeName;
    /**
     * 檔案狀態 0:待處理  1:處理完待收貨  2 :完成交易
     */
    private Integer status;
    /**
     * 建立時間
     */
     @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
     @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") 
    private String createIme;

}

多檔案上傳

html程式碼:

<div class="layui-upload-list">
                                <table class="layui-table" style="overflow: auto;">
                                    <thead>
                                        <tr>
                                            <th>檔名</th>
                                            <th>大小</th>
                                            <th>狀態</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="demoList"></tbody>

                                </table>
                            </div>

js程式碼:

layui.use(['upload','form', 'layer'], function() {
            var $ = layui.jquery,
                layer = layui.layer,
                form=layui.form,
                upload = layui.upload;
                //多檔案列表示例
            var demoListView = $('#demoList'),
                uploadListIns = upload.render({
                    elem: '#testList',
                    url: 'sysstore/uploadMultiFile',//上傳路徑
                    accept: 'file',
                    multiple: true,
                    size: 51200, //最大允許上傳的檔案大小kb
                    auto: false,
                    exts: 'pdf',//檔案型別 pdf|doc|docx
                    number: 50 ,//最多上傳檔案數為5
                    bindAction: '#testListAction',
                    before: function(obj) { //obj引數包含的資訊,跟 choose回撥完全一致,可參見上文。

                        layer.load(); //上傳loading
                        this.data={'storeId': storeId,'storeName':storeName};
                    },
                    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(''); //清空操作
                            layer.closeAll('loading'); //關閉loading
                            delete this.files[index]; //刪除檔案佇列已經上傳成功的檔案
                            return;
                        }
                        this.error(index, upload);
                        layer.closeAll('loading'); //關閉loading
                    },
                    error: function(index, upload) {
                        var tr = demoListView.find('tr#upload-' + index),
                            tds = tr.children();
                        tds.eq(2).html('<span style="color: #FF5722;">上傳失敗</span>');
                        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //顯示重傳
                        layer.closeAll('loading'); //關閉loading
                    }
                });
                });

service之-java程式碼:
request獲取檔名

public void webUploadFile(HttpServletRequest request, HttpServletResponse response,SysFileEntity sysFileEntity) {
        // TODO Auto-generated method stub
        //建立一個通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判斷 request 是否有檔案上傳,即多部分請求  
        if(multipartResolver.isMultipart(request)){  
            //轉換成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有檔名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){  
                //取得上傳檔案  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得當前上傳檔案的檔名稱  
                    String myFileName = file.getOriginalFilename();  
                    //如果名稱不為“”,說明該檔案存在,否則說明該檔案不存在  
                    if(myFileName.trim() !=""){  
                        System.out.println(myFileName);  
                        //重新命名上傳後的檔名  按照年月日時分秒進行命名
                        String fileName = BasePath.getImgPath("yyyyMMddHHmmss")+
                                Integer.toHexString(new Random().nextInt()) +"."+ myFileName.
                                substring(myFileName.lastIndexOf(".") + 1);  
                        //定義上傳路徑  
                        try {
                            String pat=FileProperties.getFilePath()+"/src/main/webapp/";//獲取檔案儲存路徑
                            String sqlPath="static/images/upload/"+BasePath.getImgPath("yyyyMMdd")+"/";
                            File fileDir=new File(pat+sqlPath);
                            if (!fileDir.exists()) { //如果不存在 則建立     
                                 fileDir.mkdirs();    
                             } 
                            String path=pat+sqlPath+fileName;
                            //存檔案
                      File localFile = new File(path);  
                            file.transferTo(localFile);
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }  
                    }  
                }  
            }  

        }
    }