转载:https://www.cnblogs.com/hutuzhu/p/4409292.html

表单提交,文件上传是一个常用又十分麻烦的功能,以前要上传文件通常都是借助插件或者flash来实现,噼里啪啦的加载一大堆东西。自从有了HTML5的FormData后,老板再也不用担心我的上传了。

FormData可以把它理解成一个虚拟的表单对象,它只有一个方法append,这个可以在浏览器console一下就知道了。我们可以通过append向FormData里面添加各种需要提交的数据。

你可以先创建一个空的 FormData 对象,然后使用 append() 方法向该对象里添加字段,如下:var oMyForm = new FormData();

oMyForm.append("username", "Groucho");
oMyForm.append("accountnum", 123456); // 数字123456被立即转换成字符串"123456"
 
// fileInputElement中已经包含了用户所选择的文件
oMyForm.append("userfile", fileInputElement.files[0]);var oReq = new XMLHttpRequest();
oReq.open("POST", "http://foo.com/submitform.php");
oReq.send(oMyForm);

如果已经有一个Form表单,只需要把这个 form 元素作为参数传入 FormData 构造函数即可:

var newFormData = new FormData(someFormElement);
var formElement = document.getElementById("myFormElement");
var oReq = new XMLHttpRequest();
oReq.open("POST", "submitform.php");
oReq.send(new FormData(formElement));

你还可以在已有表单数据的基础上,继续添加新的键值对,如下:

var formElement = document.getElementById("myFormElement");
formData = new FormData(formElement);
formData.append("serialnumber", serialNumber++);
oReq.send(formData);
<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 />
</form>
<div id="output"></div>
<a href="javascript:sendForm()">Stash the file!</a>

然后你就可以使用下面的代码来异步的上传用户所选择的文件:

function sendForm() {
  var oOutput = document.getElementById("output");
  var oData = new FormData(document.forms.namedItem("fileinfo"));
 
  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 uploading your file.<br \/>";
    }
  };
 
  oReq.send(oData);
}

你还可以使用 jQuery 来发送 FormData,但必须要正确的设置相关选项:

var fd = new FormData(document.getElementById("fileinfo"));
fd.append("CustomField", "This is some extra data");
$.ajax({
  url: "stash.php",
  type: "POST",
  data: fd,
  processData: false,  // 告诉jQuery不要去处理发送的数据
  contentType: false   // 告诉jQuery不要去设置Content-Type请求头
});

一个完整的例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FormData</title>
</head>
<body>
    <form name="form1" id="form1">  
        <p>name:<input type="text" name="name" ></p>  
        <p>gender:<input type="radio" name="gender" value="1">male <input type="radio" name="gender" value="2">female</p>  
        <p>photo:<input type="file" name="photo" id="photo"></p>  
        <p><input type="button" name="b1" value="submit" onclick="fsubmit()"></p>  
    </form>  
    <div id="result"></div>
</script>
    <script type="text/javascript">
        function fsubmit() {
            var form=document.getElementById("form1");
            var formData=new FormData(form);
            var oReq = new XMLHttpRequest();
            oReq.onreadystatechange=function(){
              if(oReq.readyState==4){
                if(oReq.status==200){
                    var json=JSON.parse(oReq.responseText);
                    var result = '';
                    // result += 'name=' + ret['name'] + '<br>';
                    // result += 'gender=' + ret['gender'] + '<br>';
                     result += '<img src="' + json['photo'] + '" width="100">';
                     $('#result').html(result);
                }
              }
            }
            oReq.open("POST", "server.php");
            oReq.send(formData); 
            return false;
        } 
    </script>
</body>
</html>
View Code

server.php文件:

<?php  
$name = isset($_POST['name'])? $_POST['name'] : '';  
$gender = isset($_POST['gender'])? $_POST['gender'] : '';  
$filename = time().substr($_FILES['photo']['name'], strrpos($_FILES['photo']['name'],'.'));  
$response = array();  
if(move_uploaded_file($_FILES['photo']['tmp_name'], $filename)){  
    $response['isSuccess'] = true;  
    $response['name'] = $name;  
    $response['gender'] = $gender;  
    $response['photo'] = $filename;  
}else{  
    $response['isSuccess'] = false;  
}  
echo json_encode($response);  
?>

 

posted on 2019-06-13 10:38  刘世涛6192  阅读(1429)  评论(0编辑  收藏  举报