基于LayUi组件java上传文件

基于LayUi组件java上传文件

  • Maven导包

    	<dependency>
    	    <groupId>commons-fileuploadgroupId>
    	    <artifactId>commons-fileuploadartifactId>
    	dependency>
    
  • jsp页面

  • js页面

    layui.use('upload', function(){
           
        var upload = layui.upload;
        //上传Excel文件
    	var uploadInst=upload.render({
           
    	    elem: '#uploadfile', //绑定元素
    	    url: projectName+'/hardware/uploadfile.do', //上传接口
    	    method:'POST',
    	    accept: 'file', //允许上传的文件类型
    	    size: 204800, //设置文件最大可允许上传的大小,单位 KB
    	    done: function(res){
            //上传完毕回调
    	    	console.log(res)
    	    	layer.msg("上传成功",{
           icon: 1});
    	        parent.location.reload();
    	    },
    
    	    error: function(){
           
    	      //请求异常回调
    	    	layer.msg("上传失败",{
           icon: 0});
    	    }
    	  });
    }
  • 配置SpringMVC上传

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	    
    	    <property name="maxUploadSizePerFile" value="5242880"/>
    	    <property name="defaultEncoding" value="UTF-8"/>
    	    <property name="resolveLazily" value="true"/>
    bean>
    
  • java后台

    /**
    	 * 上传Excel文档
    	 * @throws IOException 
    	 * @throws IllegalStateException 
    	 */
    @RequestMapping("/uploadfile.do")
    @ResponseBody
    public Map<String,String> uploadfile(@RequestParam("file") MultipartFile file,HttpServletRequest request) 
        throws IllegalStateException, IOException{
           
        if(null!=file){
           
            String fileOrigName=file.getOriginalFilename();// 文件原名称
            if (!fileOrigName.contains(".")) {
           
                throw new IllegalArgumentException("缺少后缀名");
            }
            //获取后缀名
            fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
            String newfileName =CommonFunction.strAutoInfo() +fileOrigName;
            //得到上传文件的保存目录 D:\apache-tomcat-8.0.53\webapps\QrCode\
            String uploadPath=request.getServletContext().getRealPath("");
            //获取项目名QrCode
            String projectName=request.getServletContext().getContextPath().substring(1);
            //将上传文件的保存目录换成 D:\apache-tomcat-8.0.53\webapps/uploadfile\
            String newdestPath= uploadPath.replaceAll(projectName, "uploadfile")+newfileName;
            //判断上传文件的目录是否存在
            File newfile=new File(newdestPath);
            if(!newfile.exists() && !newfile.isDirectory()){
           
                System.out.println(newfile+"目录不存在,需要创建");
                //创建目录
                newfile.mkdirs();
            }
            file.transferTo(newfile);
        }
        Map<String,String> map=new HashMap<String,String>();
        map.put("code", "0");
        map.put("msg","上传成功");
        return map;	
    }
    

你可能感兴趣的:(java基础,java-web)