layui多功能上传文件(视频,图片,pdf)

layui多功能上传文件(视频,图片,pdf)

1.前端页面html代码展示

<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>产品信息文件</legend>
    </fieldset>
    <div class="layui-form-item" id="videoUp1">
        <label class="layui-form-label" style="height: 137px; line-height: 117px">产品视频</label>
        <input name="productVideo" id="videourl1"  value="${product.productVideo }" autocomplete="off" class="layui-input" type="hidden">
        <div class=" layui-upload-drag" id="video1" style="border-left: 0px;" type="video">
            <i class="layui-icon">&#xe654;</i>
            <p>点击上传</p>
            <video id="demoVideo1" src="" style="position: absolute;height: 137px;width: 137px;margin: -106px auto auto -60px;"/>
        </div>
         <input type="button" value="预览" onclick="openVideo()" style="margin-left: 30px">
    </div>

2.前端页面js代码展示

<script type="text/javascript" src="${pageContext.request.contextPath }/statics/jquery-1.9.0.min.js"></script>
 <script type="text/javascript" src="${pageContext.request.contextPath }/statics/frame/layui/layui.all.js"></script>
 <script type="text/javascript" src="${pageContext.request.contextPath }/statics/jquery.form.js"></script>

layui.use(['form','laydate',"upload","jquery","layer", "element"], function(){
	 var $ = layui.$,
element = layui.element,
layer = layui.layer,
upload = layui.upload,
form = layui.form,
	laydate = layui.laydate;
	laydate.render({ //创建时间
    elem: '#date'
    });

//产品信息视频
    var uploadInst=upload.render({
        elem: '#video1'  
        ,url: '${pageContext.request.contextPath }/uploadAllFile/allFile'
        //上传文件大小
        , size: 10000000 
      //是否选完文件后自动上传。如果设定 false,那么需要设置 bindAction 参数来指向一个其它按钮提交上传
         ,auto: true 
         //上传所有文件
        ,accept: 'file' 
        	,before:function (obj) {
                //  $('#demo9').css('display','block').attr('src', "http://p6nngxvb7.bkt.clouddn.com/FsyjSltTtkVtzepa_w7zsnS_S7zO"); //链接(base64)http://p6nngxvb7.bkt.clouddn.com/FsyjSltTtkVtzepa_w7zsnS_S7zO
              	//上传视频设定缓冲页面
                loadIndex = layer.load(2, { shade: [0.15, '#ccc'] });
              }
        ,done: function(res){
            if(res.error>0){
                return layer.msg(res.message);
            }
                 alert("res.url:"+res.data.src); 
                $("#videourl1").val(res.data.src);
                $("#demoVideo1").attr("src",res.data.src);
                layer.msg("上传成功",{offset:['200px','450px'],icon:6});
           
            //关闭上传视频设定缓冲页面
            layer.close(loadIndex);
        }
        ,error:function () {
            //演示失败状态,并实现重传
            var demoText = $('#demoText');
            demoText.html('上传失败 重试');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
            //关闭上传视频设定缓冲页面
            layer.close(loadIndex);
        }
    });
	
})

3.java后台接口代码

@Controller
@RequestMapping("/uploadAllFile")
public class uplondFile {
	/**
	 * 信息文件上传
	 * @return {Result}
	 */
	@ResponseBody
	@RequestMapping(value = "/allFile", method = {RequestMethod.POST})
	public Object headImg(@RequestParam(value="file",required=false) MultipartFile attach, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String carPictuerUrl = null;
		//判断文件是否为空
		if(!attach.isEmpty()){
			//  String path1 =request.getSession().getServletContext().getRealPath("/");
			//System.out.println("path1:==============="+path1);
			
			  String savePath = request.getContextPath() + "/statics/uploadfiles/";
			String path = request.getSession().getServletContext().getRealPath("statics/uploadfiles");
			System.out.println("path======"+path);
			String oldFileName = attach.getOriginalFilename();//原文件名
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
			/**
			 * RandomUtils.nextInt(1, 1000000)
	         * 返回一个在指定区间内的整数
	         * startInclusive 可以返回的最小值必须是非负的
	         * endExclusive 上限(不包括)
	         */
			//String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"."+prefix;  	
			String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1,1000000)+"."+prefix;
			File targetFile = new File(path, fileName);  //创建文件
			 if(!targetFile.exists()){  //判断文件夹是否存在
                 targetFile.mkdirs();  
             }  
			 
				try {
					attach.transferTo(targetFile);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				carPictuerUrl = savePath+fileName;
				System.out.println("carPictuerUrl======"+path);
		}
	
	    HashMap<String,Object> map2=new HashMap<String,Object>();
	    HashMap<String,Object> map=new HashMap<String,Object>();
	    map.put("code",0);
	    map.put("msg","");
	    map.put("data",map2);
	    map2.put("src",carPictuerUrl);
	    return map;
	}
	
	
}

你可能感兴趣的:(java,layui,文件上传)