如何上传文件,改变input的file属性

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44037153/article/details/102671591

1.首先,在html页面编写

<input type="text" style="line-height: 36px;"  class="pc_jzxx_left_input"  id="showFileName1"/>
					            	<a href="javascript:;" class="file">选择文件 
									  <input type="file" > 
									</a>

2.在css文件里边编写

.file {
	width: 64px;
    height: 22px;
    position: relative;
    vertical-align: middle;
    display: inline-block;
    border: 1px solid #333;
    padding: 4px 10px;
    overflow: hidden;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
    border-radius: 5px;
    color: #000;
    background:#ccc; /* 一些不支持背景渐变的浏览器 */  
    background:-moz-linear-gradient(top, #fff, #ccc);  
    background:-webkit-gradient(linear, 0 0, 0 bottom, from(#fff), to(#ccc));  
    background:-o-linear-gradient(top, #fff, #ccc); 
}
.file input {    
	width: 120px !important;
    position: absolute;    
    font-size: 16px;    
    right: 0;    
    top: 0;    
    opacity: 0;
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0);
}

3.在java script编写

//上传文件
			
			$(".file").on("change","input[type='file']",function(){
			    var filePath=$(this).val();
			//判断文件类型
			    if(filePath.indexOf("docx")!=-1 || filePath.indexOf("txt")!=-1|| filePath.indexOf("jpg")!=-1|| filePath.indexOf("png")!=-1){
			        $(".fileerrorTip1").html("").hide();
			        var arr=filePath.split('\\');
			        var fileName=arr[arr.length-1];
					console.log("成功"+fileName);
			        $("#showFileName1").val(fileName);
			    }else{
//			        $("#showFileName1").val("");
			        $("#showFileName1").val("您未上传文件,或上传文件类型有误!").show();
			        return false
			    }
			})

写完之后的样子
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44037153/article/details/102671591