如何获取input,file里的文件,实现预览效果,并传给后端?
作者:互联网
单纯的事件与获取
<input type="file" name="file" id="fileUpload"> <img id="preview" src=""/>
jQuery
$("#fileUpload").change(function () { console.log($("#fileUpload")[0].files); });
原生JavaScript
var popImg = document.getElementById("fileUpload") ---------- popImg.onchange = function() { const file = document.getElementById('fileUpload'); // 获取 input(只是演示可以使用外面的 popImg) const fileObj = file.files[0]; // 获取选中的文件信息 console.log(fileObj) const windowURL = window.URL || window.webkitURL; // 兼容操作 const img = document.getElementById('preview'); // 获取img元素 if(file && fileObj) { // 判断是否为空 null const dataURl = windowURL.createObjectURL(fileObj); img.setAttribute('src',dataURl); } }
URL.createObjectURL()用法(https://blog.csdn.net/qq_39258552/article/details/84133770)
===============
1.如何实现file上传文件,预览效果
参考(https://blog.csdn.net/xiaohu12685/article/details/80328022)
<input id="pop_file" type="file" accept=".jpg,.jpeg,.png" v-on:change="uploadFile($event)" name="fileTrans" ref="file" value="" /> <img id="preview" src=""/>
js.
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>
js.
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) } })
标签:const,fileObj,预览,getElementById,params,file,input,document 来源: https://www.cnblogs.com/PasserByOne/p/12034737.html