猿问

js 怎么获取表单上传的图片的二进制数据 然后ajax提交到php? 不用上传组件

不用上传组件用js获取上传图片的二进制数据


森栏
浏览 545回答 1
1回答

米脂

用formData.append()将File转换成Blob(File) 类型,然后ajax formData&nbsp; &nbsp; var filearr = [];var myfile = document.getElementById('file');myfile.onchange = function(){&nbsp; &nbsp; var files = this.files;&nbsp;&nbsp; &nbsp; for(var i = 0;i<files.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;filearr.push(files[i]);&nbsp; &nbsp; }}function sub(){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; var formData = new FormData();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for(var i =0;i<filearr.length;i++){&nbsp; &nbsp; //提交时,我们把filearr中的数据遍历一遍&nbsp; &nbsp; &nbsp; &nbsp; formData.append("upfile[]", filearr[i]); //用append添加到formData中,就得用户最重要提交的图片了&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; };&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "1.php",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data:formData,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cache:false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//不设置缓存&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; processData: false,&nbsp; // 不处理数据&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contentType: false&nbsp; &nbsp;// 不设置内容类型&nbsp; &nbsp; });&nbsp; &nbsp;&nbsp;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答