HTML5 FormData實現文件上傳實例

表單提交,文件上傳是一個經常使用又十分麻煩的功能,之前要上傳文件一般都是藉助插件或者flash來實現,噼裏啪啦的加載一大堆東西。自從有了HTML5的FormData後,老闆不再用擔憂個人上傳了。javascript

FormData能夠把它理解成一個虛擬的表單對象,它只有一個方法append,這個能夠在瀏覽器console一下就知道了。咱們能夠經過append向FormData裏面添加各類須要提交的數據。php

你能夠先建立一個空的 FormData 對象,而後使用 append() 方法向該對象裏添加字段,以下:var oMyForm = new FormData();html

 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 構造函數便可:java

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

你還能夠在已有表單數據的基礎上,繼續添加新的鍵值對,以下:ajax

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>

而後你就可使用下面的代碼來異步的上傳用戶所選擇的文件:json

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請求頭
});

 一個完整的例子:app

<!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>

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);  
?>
相關文章
相關標籤/搜索