vue中使用input[type="file"]实现文件上传功能


Posted in Javascript onSeptember 10, 2018

注意:input[type="file"] 标签中的属性accept="application/msword,application/pdf" 在pc上正常,但是在手机ios和android上这个文件格式限制会被忽略,所以需要在js中增加格式的判断,以及对应显示样式的设置.(我也是刚发现,如果有遇到这个问题的可以参考下---下面有更改:)

vue中使用input[type="file"]实现文件上传功能

```

<template>
<div id="my-careers">
<head-top id="header">
<i slot="left" class="iconfont icon-back"></i>
<span slot="title">Apply Online</span>
<i slot="right" class="icon-right fa"></i>
</head-top>
<div class="content">
<form @submit.prevent="onSubmit" id="fileForm" >
<div class="form">
<h3>Customer Car Manager</h3>
<ul class="form-group">
<li class="info-name">
<input type="text" v-focus :class="{errli:form.nameErr}" name="name" placeholder="Name" v-model="applyInfo.name" >
<p class="errP" v-if="form.nameErr">{{form.nameMsg}}</p>
</li>
<li class="info-email">
<input type="text" :class="{errli:form.emailErr}" name="email" placeholder="Email Address" v-model="applyInfo.email" >
<p class="errP" v-if="form.emailErr">{{form.emailMsg}}</p>
</li>
<li class="info-mobile">
<input type="number" :class="{errli:form.mobileErr}" name="mobile" placeholder="Mobile Number" v-model="applyInfo.mobile" >
<p class="errP" v-if="form.mobileErr">{{form.mobileMsg}}</p>
</li>
<li class="info-location">
<input type="text" :class="{errli:form.locationErr}" name="location" placeholder="Current Location" v-model="applyInfo.location" >
<p class="errP" v-if="form.locationErr">{{form.locationMsg}}</p>
</li>
<li class="reason-li" :class="{'info-reason':applyInfo.joinReason.split('').length >= 300}">
<textarea :class="{errli:form.joinReasonErr}" name="joinReason" v-model="applyInfo.joinReason" rows="5" cols="20" placeholder="Why do you want to join HappyEasy Go?" ></textarea>
<span>{{wordNumber}}</span>
<p class="errP" v-if="form.joinReasonErr">{{form.joinReasonMsg}}</p>
</li>
<li class="info-link">
<input type="text" :class="{errli:form.linkedinUrlErr}" name="linkedinUrl" placeholder="LinkedIn URL (Optional)" v-model="applyInfo.linkedinUrl" >
<p class="errP" v-if="form.linkedinUrlErr" >{{form.linkedinUrlMsg}}</p>
</li>
<li class="info-file" >
<span class="file-span" v-if="fileObj != null" v-show="isSelectFile">{{fileObj.name}}</span>
<p v-show="!isSelectFile">Attach Resume</p>
<p v-show="!isSelectFile">(Microsoft Word or PDF file is allowed (5MB))</p>
<p><input type="file" id="upfile" accept="application/msword,application/pdf" name="upfile" @change="selectFile" ><span>Upload file</span> or drag and drop</p>
</li>
<li class="info-btns flex space-between" >
<button @click="infoJustify" :class="{active:true}">Submit</button>
</li>
</ul>
</div>
</form>
</div>
<div class="career-cover" v-show="showDialog"></div>
<div class="career-dialog" v-show="showDialog">
<div class="d-top">
Apply Online
</div>
<div class="d-center">
Thank you for applying to this job!
</div>
<div class="d-bottom">
<button @click="applySuccess">OK</button>
</div>
<img :src="dialogBg" alt="">
</div>
</div>
</template>
```
<script>
import {Toast, Indicator} from 'mint-ui';
import { Reg } from '../../models/utils/Reg.js';
import headTop from "Components/head/header.vue";
import { DomainManager } from '../../request/DomainManager';
export default {
components:{
headTop,
},
data(){
return {
arr:[],
fileObj:null,
showDialog:false,
isSelectFile:false,
dialogBg:require('../../assets/images/joinus/join-character.png'),
applyInfo:{// form表单绑定的数据,linkedinUrl是可选参数
name:"",
email:"",
mobile:"",
location:"",
joinReason:"",
linkedinUrl:"",
positionId:null,
departmentId:null,
},
form:{// 对应input错误信息的设置
nameMsg:"Please enter a valid name",nameErr:false,
emailMsg:"Please enter a valid Email Address",emailErr:false,
mobileMsg:"Please enter a valid Mobile Number",mobileErr:false,
locationMsg:"Please enter your current location",locationErr:false,
joinReasonMsg:"Please write down your reason",joinReasonErr:false,
linkedinUrlMsg:"",linkedinUrlErr:false,
fileMsg:"Microsoft Word or PDF file is allowed (<5MB)",
fileNull:"Please Upload your attach resume",
submitFail:"Something's wrong, Please try it again",
submitting:"Uploading...Please wait",
},
}
},
computed:{
wordNumber(){// 动态计算textarea的字数
let number = this.applyInfo.joinReason.split("").length;
return (300 - number);
}
},
watch:{
applyInfo:{// 配合限制textarea的字数
handler:function(val,oldV){
if(this.applyInfo.joinReason.split('').length >= 300){
this.applyInfo.joinReason = this.applyInfo.joinReason.substr(0,300);
}
if(this.applyInfo.name != ""){
this.form.nameErr = false;
}
if(this.applyInfo.email != ""){
this.form.emailErr = false;
}
if(this.applyInfo.mobile != ""){
this.form.mobileErr = false;
}
if(this.applyInfo.location != ""){
this.form.locationErr = false;
}
if(this.applyInfo.joinReason != ""){
this.form.joinReasonErr = false;
}
},
deep:true
}
},
methods:{
selectFile(){
// 注意这里想要获取formDate的数据格式,那么input必须加上name属性,且name值对应绑定的v-model数据名字
let size;
this.fileObj = document.getElementById("upfile").files[0];//获取文件信息
if(this.fileObj){ // 原来的代码,稍作调整
size = (this.fileObj.size / (1024 * 1024)).toFixed(2);
let idx = this.fileObj.name.lastIndexOf(".");
if (idx != -1){
let ext = this.fileObj.name.substr(idx+1).toUpperCase();
ext = ext.toLowerCase( );
if (ext != 'pdf' && ext != 'doc' && ext !='docx'){
Toast("You can upload.pdf,.doc,.docx files only.")
if(this.arr.length >= 1){
this.fileObj = this.arr[0];
}else{
this.isSelectFile = false;
}
}else{
if(size >= 5){
Toast("Please select files within 5M")
if(this.arr.length >= 1){
this.fileObj = this.arr[0];
}else{
this.isSelectFile = false;
}
}else{
this.arr[0] = this.fileObj;
this.isSelectFile = true;
}
}
}
}else{// 当打开本地文件,点击取消不选择时,显示已经选择过的文件,如果没有这个if则显示没有文件的状态
if(this.arr.length >= 1){
this.fileObj = this.arr[0];
}else{
this.isSelectFile = false;
}
}
},
infoJustify(){
// 判断input的内容正确与否
if(this.applyInfo.name == ""){
this.form.nameErr = true;
}else if(this.applyInfo.email == "" || !Reg.email.test(this.applyInfo.email)){
this.form.nameErr = false;
this.form.emailErr = true;
}else if(this.applyInfo.mobile == "" || !Reg.ChinaMobile.test(this.applyInfo.mobile)){
this.form.nameErr = false;
this.form.emailErr = false;
this.form.mobileErr = true;
}else if(this.applyInfo.location == ""){
this.form.nameErr = false;
this.form.emailErr = false;
this.form.mobileErr = false;
this.form.locationErr = true;
}else if(this.applyInfo.joinReason == ""){
this.form.nameErr = false;
this.form.emailErr = false;
this.form.mobileErr = false;
this.form.locationErr = false;
this.form.joinReasonErr = true;
}else if(this.fileObj == null){
this.form.nameErr = false;
this.form.emailErr = false;
this.form.mobileErr = false;
this.form.locationErr = false;
this.form.joinReasonErr = false;
this.form.linkedinUrlErr = false;
Toast({
message:"Please select the file",
duration:1500
});
}else{
this.fileUpload();
}
},
fileUpload(){
//这里是只上传文件的步骤
// let formData = new FormData();
// formData.append("upfile",this.fileObj);
// 这里上传文件并且需要传更多参数的时候
let fileForm = document.getElementById("fileForm");// 获取整个form表单数据,记住input都需要name属性
let url = DomainManager.saveCareer();// 上传服务器接口
let params = this.$route.query;
let formData = new FormData(fileForm);
formData.append("positionId",params.positionId);// 这就是给formData添加新的表单数据的形式
formData.append("departmentId",params.departmentId);
this.$axios({
url:url,
method:"post",
data:formData,
headers:{"Content-Type":"multipart/form-data"},
}).then(res => {
if(res.success){
this.showDialog = true;
}else{
}
}).catch(err =>{
console.log(err)
});
},
applySuccess(){
this.showDialog = false;
},
onSubmit(){
// 取消form表单的自动提交功能
return false;
}
},
directives:{
focus: {
inserted: function (el) {
el.focus()
}
}
}
}
</script>
<style lang="less" scoped>
#my-careers{
.content{
padding: 0.5rem 0.2rem 0;
text-align: left;
h3{
font-size:0.16rem;
padding: 0.15rem 0;
}
.form-group{
li{
position: relative;
width:100%;
margin-bottom:0.24rem;
color:#999;
display:flex;
input,textarea{
width:93.5%;
padding:0.09rem 3%;
border:1px solid #ddd;
border-radius:0.03rem;
vertical-align: top;
font-size: 0.14rem;
}
*::placeholder{
color:#999;
}
}
.reason-li{
textarea{font-family: inherit;}
span{
position:absolute;
font-size:0.14rem;
right: 0.05rem;
bottom: 0;
}
}
.info-reason{
textarea{resize: none;}
}
.info-file{
display:block;
border:1px dashed #eee;
font-size: 0.14rem;
text-align: center;
padding:0.13rem 0 0.1rem;
margin-bottom:0.15rem;
height:0.59rem;
.file-span{
color:#999;
background:#fff;
padding:0.02rem 0.1rem;
margin-bottom:0.05rem;
border:1px solid #ddd;
border-radius:3px;
box-shadow:0 2px 5px #999;
}
p{
position: relative;
line-height:0.2rem;
color:#999;
span{
color:#0b9d78;
}
input{
position: absolute;
width:0.66rem;
opacity: 0;
display:inline-block;
padding:0;
border:0;
}
}
}
.info-btns{
margin-bottom:0;
button{
width:2rem;
padding:0.06rem 0;
font-size: 0.16rem;
color:#999;
background: #eee;
border-radius: 0.03rem;
margin:auto;
}
.active{
color:#fff;
background: #ffa000;
}
}
.errli{
border:1px solid #d32f2f;
}
.errP{
position: absolute;
font-size:0.14rem;
color:#d32f2f;
left: 0;
bottom: -0.2rem;
padding-left:3%;
}
}
}
.career-cover{
width: 100%;
height: 100%;
position:absolute;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
z-index:10;
}
.career-dialog{
width:2.8rem;
position: absolute;
top: 35%;
left: 0;
right: 0;
margin:auto;
z-index:11;
background:rgba(255, 255, 255, 1);
padding:0.3rem 0.2rem;
border-radius:5px;
overflow: hidden;
.d-top{
font-size: 0.14rem;
color:#666;
display:flex;
align-items: center;
font-weight: bold;
}
.d-top::after{
display:block;
content:"";
flex:1;
margin-left:0.15rem;
border-top:1px solid #999;
}
.d-center{
padding:0.3rem 0;
color:#0b9d78;
font-size: 0.16rem;
font-weight: bold;
}
.d-bottom{
position: relative;
height:0.3rem;
margin-bottom:0.15rem;
button{
position: absolute;
width:2rem;
padding:0.1rem 0;
font-size: 0.16rem;
color:#fff;
background: #ffa000;
border-radius:3px;
left: 0;
right: 0;
margin:auto;
z-index:9;
}
}
img{
opacity: 0.2;
position:absolute;
width:1.8rem;
top: 0.5rem;
right: -0.1rem;
z-index:8;
}
}
}
</style>

总结

以上所述是小编给大家介绍的vue中使用input[type="file"]实现文件上传功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
JavaScript 克隆数组最简单的方法
Feb 12 Javascript
jquery 模式对话框终极版实现代码
Sep 28 Javascript
Easy.Ajax 部分源代码 支持文件上传功能, 兼容所有主流浏览器
Feb 24 Javascript
jQuery实现提交按钮点击后变成正在处理字样并禁止点击的方法
Mar 24 Javascript
深入浅析JavaScript中数据共享和数据传递
Apr 25 Javascript
浅析jquery unbind()方法移除元素绑定的事件
May 24 Javascript
ashx文件获取$.ajax()方法发送的数据
May 26 Javascript
jquery购物车结算功能实现方法
Oct 29 Javascript
Puppet的一些技巧
Sep 17 Javascript
微信小程序实现列表页的点赞和取消点赞功能
Nov 02 Javascript
Vue2(三)实现子菜单展开收缩,带动画效果实现方法
Apr 28 Javascript
vue 自定义的组件绑定点击事件
Apr 21 Vue.js
详解Eslint 配置及规则说明
Sep 10 #Javascript
bootstrap自定义样式之bootstrap实现侧边导航栏功能
Sep 10 #Javascript
vue弹窗组件的实现示例代码
Sep 10 #Javascript
vue axios数据请求及vue中使用axios的方法
Sep 10 #Javascript
vue插件实现v-model功能
Sep 10 #Javascript
在Angular中使用JWT认证方法示例
Sep 10 #Javascript
详解vue-router传参的两种方式
Sep 10 #Javascript
You might like
php制作文本式留言板
2015/03/18 PHP
PHP实现获取并生成数据库字典的方法
2016/05/04 PHP
javascript 面向对象编程 function也是类
2009/09/17 Javascript
js 父窗口控制子窗口的行为-打开,关闭,重定位,回复
2010/04/20 Javascript
Js获取事件对象代码
2010/08/05 Javascript
jQuery EasyUI API 中文文档 - NumberSpinner数值微调器使用介绍
2011/10/21 Javascript
jquery动态调整div大小使其宽度始终为浏览器宽度
2014/06/06 Javascript
javascript数组详解
2014/10/22 Javascript
javascript简单写的判断电话号码实例
2017/05/24 Javascript
Vue.js 中的 $watch使用方法
2017/05/25 Javascript
JavaScript判断浏览器和hack滚动条的写法
2017/07/23 Javascript
微信小程序页面缩放式侧滑效果的实现代码
2018/11/15 Javascript
利用JavaScript的Map提升性能的方法详解
2019/08/14 Javascript
javascript随机变色实例代码
2019/10/15 Javascript
JavaScript DOM常用操作代码汇总
2020/07/03 Javascript
vue路由切换时取消之前的所有请求操作
2020/09/01 Javascript
[03:01]2014DOTA2国际邀请赛 DC:我是核弹粉,为Burning和国土祝福
2014/07/13 DOTA
[56:13]DOTA2-DPC中国联赛定级赛 LBZS vs Phoenix BO3第一场 1月10日
2021/03/11 DOTA
python创建临时文件夹的方法
2015/07/06 Python
利用Python爬取可用的代理IP
2016/08/18 Python
Python 调用 zabbix api的方法示例
2019/01/06 Python
对Python闭包与延迟绑定的方法详解
2019/01/07 Python
利用python求积分的实例
2019/07/03 Python
Python替换月份为英文缩写的实现方法
2019/07/15 Python
python通过txt文件批量安装依赖包的实现步骤
2019/08/13 Python
Tensorflow tensor 数学运算和逻辑运算方式
2020/06/30 Python
Nuts.com:优质散装,批发坚果、干果和巧克力等
2017/03/21 全球购物
财务会计专业应届毕业生求职信
2013/10/18 职场文书
职业女性的职业规划
2014/03/04 职场文书
鸿星尔克广告词
2014/03/21 职场文书
教师廉洁自律承诺书
2014/05/26 职场文书
企业法人代表任命书
2014/06/06 职场文书
药品营销专业毕业生自荐信
2014/07/02 职场文书
王兆力在市委党的群众路线教育实践活动总结大会上的讲话稿
2014/10/25 职场文书
MySQL去除密码登录告警的方法
2022/04/20 MySQL
MySQL主从切换的超详细步骤
2022/06/28 MySQL