Layui文件上传(java)

Layui文件上传的一些参数,这里不过多介绍,详情可看Layui文件上传参数设置,这里主要介绍【springMVC】上传文件

spring配置

springmvc.xml加入配置

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

单文件上传

html代码:

  <div class="layui-upload" style="margin-left: 30px;margin-right: 30px;">
   <div style="margin-top: 171px;float: left;">div>
  <div class="layui-upload-list" style="float: left;">
    class="layui-upload-img" id="demo1" style="width: 200px;height: 200px;margin: 0 10px 10px 0;">
    

id="demoText">

"hidden" name="pic" id="pic" value="${store.pic }"> div> <div style="float: left;margin-top: 171px;">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('上传失败 重试');
              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 = $([''">', '' + file.name + '', '' + (file.size / 1014).toFixed(1) + 'kb', '等待上传', '', '', '', '', ''].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('上传成功');
                            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('上传失败');
                        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();
                        }  
                    }  
                }  
            }  

        }
    }

你可能感兴趣的:(java,前端,工作记录)