fileinput实现文件上传

本文介绍了如何使用fileinput组件进行文件上传操作,包括前端js的实现和后台数据的接收与保存,最后展示了上传成功的实际效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.引入fileinput相关的css和js(如需要中文显示,则引入对应的中文js包)

2.前端js上传的主要实现方法如下:

$(function () {
			loadRole();	
			initFileInput("pic_path","../SalesImageController/SalesImageController_uploadFile.do");
		});
	  
		
	    //关闭
 		function cancle(){
 			history.back();
	    }
 		
	    
		
		

	   function initFileInput(ctrlName, uploadUrl) {  	    
            var control = $('#' + ctrlName); 
            control.fileinput({  
                resizeImage : true,  
                maxImageWidth : 200,  
                maxImageHeight : 200,  
                resizePreference : 'width',  
                language : 'zh', //设置语言  
                uploadUrl : uploadUrl,  
                uploadAsync : true,  
                allowedFileExtensions : [ 'png', 'jpeg', 'gif', 'jpg' ],//接收的文件后缀  
                showUpload : true, //是否显示上传按钮  
                showCaption : true,//是否显示标题  
                browseClass : "btn btn-primary", //按钮样式  
                previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",  
                maxFileCount : 10,  
                msgFilesTooMany : "选择文件超过了最大数量",  
                maxFileSize : 104857600, //设置最大上传值
                layoutTemplates:{
                	 actionDelete: '',//去除上传预览的缩列图中的删除图标	
                     actionUpload: '',//去除上传预览的缩列图中的上传图标	
                   //  actionZoom: '',//去除上传预览的缩列图中的预览图标	
                },
                uploadExtraData: function(previewId, index) {   //额外参数的关键点
                    var data = {
                		messageTitle : $("#messageTitle").val(),
               	    };
                    return data;
                },
	        }).on('filebatchpreupload', function(event, data) {
	        	if($("#messageTitle").val()==''|| $("#messageTitle").val()==null){ 
	        		return {
	                      message: "上传失败,请填写标题!", 
	                      data:{} 
	                  };
	          }else{
		            var n = data.files.length, files = n > 1 ? n + '个文件' : '1个文件';
		            if (!window.confirm("确定上传 " + files + "?")) {
		                return {
		                    message: "上传取消!!", // upload error message
		                    data:{} // any other data to send that can be referred in `filecustomerror`
		                };
		            }else{
		            	if(data.success==false){
		            		 return {
				                message: data.error, // upload error message
				                data:{} // any other data to send that can be referred in `filecustomerror`
				             };
		            	}
		            }
	        	}
	        });   
        };  
		
	</script>
     </head>
<body style="height: 100%;background-color: white;" >
	 <!-------------------------------搜索框----------------------------------->
      <div class="panel panel-default" style="height: 100%;overflow: scroll;">
				<div class="panel-body">
					<form id="addSalesMessageForm" class="form-inline" enctype='multipart/form-data'>
					 <div class="form-group" style="width:100%">
						 <label for="messageTitle"class="col-sm-1 control-label">标题:</label>
					  <input type="text" class="form-control" ID="messageTitle" name="messageTitle" style="width:81%;"  />
		        		 </div>	
					 <div class="form-group" style="width: 100%;margin-top:1%;">	
						 <label for="memo"class="col-sm-1 control-label" >上传图片:</label>
						 <input id="pic_path" name="pic_path" type="file" multiple class="file-loading" style="height:auto">  							
					 </div>
                   <div >
				</div>
				
				</form>
				<div style="width: 100%;text-align: center;position: absolute;bottom: 1px;">				
					<a href="javascript:void(0);" class="btn btn-default"  onclick="cancle();">关闭</a>
				</div>
        	</div>
        	
        	
        	
    </div>
	
	
</body>
</html>


3.后台接收保存文件相关数据的实现方法如下:

/*** 
     * 上传文件 用@RequestParam注解来指定表单上的pic_path为MultipartFile 
     * @author fan
     * @date 2018-01-24
     */  
    @ResponseBody
    @RequestMapping(value="SalesImageController_uploadFile")    
    public  Map<String,Object> uploadFile(HttpSession session,@RequestParam("pic_path")MultipartFile myfile,
    		@RequestParam("messageTitle")String messageTitle) throws IllegalStateException, IOException{
    	PageData pd = new PageData();
		pd = this.getPageData();
		IUser user=this.getApUser();
        Map<String,Object> map=new HashMap<String,Object>();
    	//原始名称  
        String oldFileName = myfile.getOriginalFilename(); //获取上传文件的原名 
        String file_path = CommonUtil.getConfig("common","SCROLL_DIAGRAM_PATH");//文件基本上传路径 
        //文件存储的真实路径
        File real_path =new File(file_path ) ;
       //上传文档
        if(myfile!=null && oldFileName!=null && oldFileName.length()>0){
        	Date date = new Date();
        	String uuid = UUID.randomUUID().toString().replace("-", "");
            //新的文档名称  
            // String newFileName = user_path+"_"+sdf.format(date)+oldFileName.substring(oldFileName.lastIndexOf(".")); 
            String newFileName = uuid+oldFileName.substring(oldFileName.lastIndexOf(".")); 
            String  suffixName = oldFileName.substring(oldFileName.lastIndexOf(".")+1);
            if(!real_path.isDirectory()){
            	real_path.mkdirs();   
            }
            //新文档
            File newFile = new File(real_path+"/"+newFileName); 
            String origPath = real_path+"/"+newFileName;
            //将内存中的数据写入磁盘  
            myfile.transferTo(newFile);     
        	try {
                 //将文档上传的信息保存到数据库表中(省略)         	
                map.put("result", true);
        	}catch (Exception e) {
				map.put("error", "文档上传失败,请勿重复上传,尽快联系系统管理员!"+e);
				 // 路径为文件且不为空则进行删除  
			    if (newFile.isFile() && newFile.exists()) {  
			    	newFile.delete();   
			    }  
				 map.put("result", false);
				e.printStackTrace();
			}
			
        }
        return map;
    }



实现效果图如下:



上传成功


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值