有时候我们想点击一个按钮打开目录文件选择文件的路径显示,方法如下:
如果使用原生js:
文件上传比较丑,样式调整时会有一个获取文件名,或者包含文件路径的文件名的方法
html代码
<div class="file-box">
<form id="uploadForm">
<input type="text" id="textfield" class="txt" /> <input type="button" class="btn" value="浏览..." /> <input type="file" name="file" class="file" id="fileField" onchange="document.getElementById('textfield').value=this.files[0].name"/> <input type="submit" class="btn" value="上传" /> </form> </div>
CSS样式
.file-box{ position:relative;width:340px;margin:20px;}
.txt{ height:28px;line-height:28px; border:1px solid #cdcdcd; width:180px;}
.btn{width:70px; color:#fff; border:0 none;height:28px; line-height:16px!important;cursor:pointer;}
.btn:hover{background-color:#63bfff;color:#fff;}
.file{ position:absolute; top:0; right:85px; height:30px;line-height:30px; filter:alpha(opacity:0);opacity: 0;width:254px }
效果图
只获取文件名
document.getElementById('fileField').files[0].name
获取带路径的文件名
document.getElementById('fileField').value
在vue中使用:
html:
<el-form-item label="存储路径">
<el-input v-model="dataForm.road"></el-input>
<input type="file" id="file_input" @change='uproad()'>
</el-form-item>
js:
uproad(){
this.dataForm.road=document.getElementById('file_input').value;
},
结果:
分割线:
说下怎么更换file按钮上的文字。
解决方法:
1)页面上放个隐藏的<input type=“file” />
2)然后加上一个文本input(type="text")和一个按钮input(type="button")
3)点按钮的时候调用<input type=file />的click选择文件
4)在<input type=file />的onchange事件中把其值显示在文本input中
5)注意把文本input设置成只读的,防止出错
<form name="form1">
<input type="file" name="picpath" id="picpath" style="display:none;" onChange="document.form1.path.value=this.value">
<input name="path" readonly>
<input type="button" value="上传照片" οnclick="document.form1.picpath.click()">
</form>
我这里是vue项目采用:
效果:
这样也可以隐藏后边的