原生js上传文件,使用new FormData()

 当创建一个内容较多的表单,表单里面又有了文件上传,文件上传也需要表单提交,单一的上传文件很好操作;

<form action="接口" enctype="multipart/form-data" method="post">
    <input type="file" name="uploadFile"/>
    <input type="submit" value="提交"/>
</form>

但是,正常提交数据和上传文件不是一个接口,后台接收参数的方式也是不一样的;这就需要两个form表单,但是form表单是不能嵌套的;还有就是表单的内容是按照顺序排列的,穿件两个独立的表单,写样式会很麻烦;

  因此需要一个动态创建form表的js代码

这个方法只支持到IE10,IE10以下不支持new FormData();

//获取文件
function addFile() {
   document.getElementById('test1').value = "";
var file = document.querySelector('input[type=file]').files[0];//IE10以下不支持
var typeStr="image/jpg,image/png,image/gif,image/jpeg";
if(typeStr.indexOf(file.type)>=0){
document.getElementById('test1').value = file.name;
if (file.size > 2097152) {
alert("上传的文件不能大于2M");
return;
}else{
     upload(path,file)
    }
}else{
alert("请上传格式为jpg、png、gif、jpeg的图片");
}

//上传文件
function
upload(path,theFormFile) { var fd = new FormData(); fd.append('file1', theFormFile);//上传的文件: 键名,键值 var url = path;//接口 url = url ? url : ''; var XHR = null; if (window.XMLHttpRequest) { // 非IE内核 XHR = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE内核,这里早期IE版本不同,具体可以查下 XHR = new ActiveXObject("Microsoft.XMLHTTP"); } else { XHR = null; } if (XHR) { XHR.open("POST", url); XHR.onreadystatechange = function() { if (XHR.readyState == 4 && XHR.status == 200) { var resultValue = XHR.responseText; var data = JSON.parse(resultValue); XHR = null; } } XHR.send(fd); } };
原文地址:https://www.cnblogs.com/lengyue0030/p/6885107.html