Ajax请求参数为文件类型

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 对象的参数。但无论是xhr 1级还是2级,send()的参数都不能是文件对象类型。)

 <div>
  <input type="file" id="myfile">
  <input type="button" value="上传" onclick="HeadPortraitPicture()">
</div>
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

 3、浏览器出于安全考虑,选择上传的图片必须由可以来选择,也就是说标签中不能设置默认文件,js中也不能修改 input[type="file"] 表单的value属性值,

  value属性是一个只读属性。     参考:https://segmentfault.com/q/1010000009883479

4、使用jquery提交FormData数据    : 参考链接

  html的代码和第2点的一样的

    function HeadPortraitPicture() {
        var fd = new FormData();
        fd.append("file", document.getElementById('myfile').files[0]);//这是获取上传的文件
    fd.append("api_id", "198ae4a939f54cf99116fdefffcb3e40");//这是获取上传的文件
    fd.append("api_secret", "86090f1e697d436f85b0552d934a7df4");//这是获取上传的文件
        $.ajax({
          url: "https://cloudapi.linkface.cn/ocr/idcard",
          type: 'POST',
          data: fd,
          contentType: false,
          async:true,
          processData: false,
          success: function (res) {
                console.log(res);
            }
        });
    }
View Code

猜你喜欢

转载自www.cnblogs.com/wfblog/p/9242204.html
今日推荐