1、图片用get请求,回调函数中返回的数据就是流文件,在回调函数中再使用post请求

2、JS将文件像form表单一样提交到后台  :  https://www.cnblogs.com/HeKaiYue/p/7147752.html  (亲测有效)

  这里使用到XMLHttpRequest 2级中的  FormData 对象  : https://blog.csdn.net/saharalili/article/details/79002568

  (题外话:个人经验 XMLHttpRequest 1级中的send()方法只能是字符串作为参数,一般是形如 "user="+username+"&pwd="+password 这种参数。参考

       XMLHttpRequest 2级中send()方法的参数增加了FormData 对象的参数。ajax要发送文件,必须把请求体转换为 FormData 对象发送。)

 <div>
  <input type="file" id="myfile">
  <input type="button" value="上传" onclick="HeadPortraitPicture()">
</div>
Ajax请求参数为文件类型
function HeadPortraitPicture()
{
  if (document.getElementById('myfile').files[0] != null) {//判断上传的文件是否为空
    var fd = new FormData();
    fd.append("file", document.getElementById('myfile').files[0]);//这是获取上传的文件
    fd.append("api_id", "198ae4a939f54cf99116fdefffcb3e40");//这是获取上传的文件
    fd.append("api_secret", "86090f1e697d436f85b0552d934a7df4");//这是获取上传的文件
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://cloudapi.linkface.cn/ocr/idcard");//要传到后台方法的路径
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);//返回来的数据
    xhr.addEventListener("error", uploadFailed, false);//返回异常
    xhr.addEventListener("abort", uploadCanceled, false);//返回连接异常
    xhr.send(fd);//放入文件发送到后台
  }
}
function uploadProgress(evt) {
  if (evt.lengthComputable) {
    //var percentComplete = Math.round(evt.loaded * 100 / evt.total);//可以在这里接收进度条数据
  }
  else {
    alert("无法计算!");
  }
}
function uploadComplete(evt) {
  /* 服务器返回数据*/
  var message = evt.target.responseText;//接收返回来的数据
}

function uploadFailed(evt) {
  alert("上传出错.");
}

function uploadCanceled(evt) {
  alert("上传已由用户或浏览器取消删除连接.");
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-01
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
  • 2021-09-09
相关资源
相似解决方案