如何在IE 10中发送发布请求?

问题描述 投票:1回答:1

如何在IE 10.0.9200中使用FormData()发送发帖请求?

HTML代码:

<form id="myform" enctype="multipart/form-data" method="post">
    <input id="fileInput" type="file" name="avatar" style="width:100px; height:30px"/>  
    <div class="hr hr-12 dotted"></div>
    <button type="submit" class="btn btn-sm btn-primary">Submit</button>
    <button type="reset" class="btn btn-sm">Reset</button>
</form>

Javascript代码:发送表单数据以上传图像,并在提交图像后将其提交到服务器,请帮助我了解如何处理formdata()并发布IE 10.0.9200的请求。

var fd = new FormData($form.get(0));

deferred = $.ajax({
            url: submit_url,
            type: $form.attr('method'),
            processData: false,
            contentType: false,
            dataType: 'json',
            data: fd,
            xhr: function() {
                var req = $.ajaxSettings.xhr();
                if (req && req.upload) {
                    req.upload.addEventListener('progress', function(e) {
                        if(e.lengthComputable) {    
                            var done = e.loaded || e.position, total = e.total || e.totalSize;
                            var percent = parseInt((done/total)*100) + '%';
                            //percentage of uploaded file
                        }
                    }, false);
                }
                return req;
            },
            beforeSend : function() {
            },
            success : function() {

            }
        })
javascript jquery ajax post form-data
1个回答
1
投票

使用FormData对象发送文件

您还可以使用FormData发送文件。只需在您的:

中包含文件type的元素
<form enctype="multipart/form-data" method="post" name="fileinfo">
  <label>Your email address:</label>
  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
  <label>Custom file label:</label>
  <input type="text" name="filelabel" size="12" maxlength="32" /><br />
  <label>File to stash:</label>
  <input type="file" name="file" required />
  <input type="submit" value="Stash the file!" />
</form>
<div></div>

Then you can send it using code like the following:

var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {

  var oOutput = document.querySelector("div"),
      oData = new FormData(form);

  oData.append("CustomField", "This is some extra data");

  var oReq = new XMLHttpRequest();
  oReq.open("POST", "stash.php", true);
  oReq.onload = function(oEvent) {
    if (oReq.status == 200) {
      oOutput.innerHTML = "Uploaded!";
    } else {
      oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
    }
  };

  oReq.send(oData);
  ev.preventDefault();
}, false);

您还可以将File或Blob直接附加到FormData对象,如下所示:

data.append("myfile", myBlob, "filename.txt");

参考链接-https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

© www.soinside.com 2019 - 2024. All rights reserved.