1.如何实现file上传文件,预览效果
<input id="pop_file" type="file" accept=".jpg,.jpeg,.png" v-on:change="uploadFile($event)" name="fileTrans" ref="file" value="" /> <img id="preview" src=""/>
uploadFile:function(ev){ var that = this; const file = document.getElementById('pop_file'); const fileObj = file.files[0]; const windowURL = window.URL || window.webkitURL; const img = document.getElementById('preview'); if(file && fileObj) { const dataURl = windowURL.createObjectURL(fileObj); img.setAttribute('src',dataURl); } }
2.获取到file里的文件,使用异步的请求实现局部刷新的效果
<form @submit.prevent="addbanner()"> <input id="pop_file" type="file" accept=".jpg,.jpeg,.png" v-on:change="uploadFile($event)" name="fileTrans" ref="file" value="" /> <input class="pop_but" type="submit" value="提交"/> </form>
addbanner: function(ev) { var oFiles = document.getElementById("pop_file").files; var params = new FormData(); params.append('file',oFiles[0]); axios({ method: 'post', url: 'http://请求路径/admin/BannerApi/actionBannerSave', headers: { 'Content-type': 'application/x-www-form-urlencoded;charset=UTf-8' }, data: params }) .then(function(response) { console.log(response) }) }
如果是ajax请求的话
var oFiles = document.getElementById("pop_file").files; var params = new FormData(); params.append('file',oFiles[0]); $.ajax({ type:'post', url:'http://api.tianshuai.com.cn/admin/BannerApi/actionBannerSave', data:params, cache: false, contentType: false, processData: false, success:function(data){ console.log(data) } })