formData ajax送資料

前陣子因為有個需求

送出表單的時候不想要畫面重刷,資料及時回填到頁面來。

這樣的話就是要用到ajax的技術,

單純的文字資料沒什麼問題,

但是如果要用圖片或影片的話,就必須麻煩一些了。

資料找了好久找到了一篇使用formData 和 XMLHTTPRequest

資料來源 : https://gist.github.com/ebidel/2410898

這個網站裡面有兩段code

handle_file_upload.php

<?php
$fileName = $_FILES['afile']['name'];
$fileType = $_FILES['afile']['type'];
$fileContent = file_get_contents($_FILES['afile']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);

$json = json_encode(array(
  'name' => $fileName,
  'type' => $fileType,
  'dataUrl' => $dataUrl,
  'username' => $_REQUEST['username'],
  'accountnum' => $_REQUEST['accountnum']
));

echo $json;
?>

第一行第二行都是在宣告一個變數來接post過來的資料

第三行是把圖片做成實體檔案到指定路徑

第四行是把圖片轉成base64

第五行開始到倒數第二行都是在建立一個json陣列的資料

最後一行是把json的資料show出來


<!DOCTYPE html>
<!--
Copyright 2012 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Author: Eric Bidelman (ericbidelman@chromium.org)
-->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title>xhr.send(FormData) Example</title>
</head>
<body>

<input type="file" name="afile" id="afile" accept="image/*"/>

<script>
//當id="afile"的物件它產生了change的動作時執行
document.querySelector('#afile').addEventListener('change', function(e) {
  //取得檔案
  var file = this.files[0];
  //呼叫formData
  var fd = new FormData();
  //建立一個name是afile的欄位
  fd.append("afile", file);
  // These extra params aren't necessary but show that you can include other data.
  fd.append("username", "Groucho");
  fd.append("accountnum", 123456);
  
  //呼叫XMLHttpRequest
var xhr = new XMLHttpRequest();
  //POST檔案到handle_file_upload.php(上面那一段code)
  xhr.open('POST', 'handle_file_upload.php', true);
  //post檔案的進度
  xhr.upload.onprogress = function(e) {
    if (e.lengthComputable) {
      var percentComplete = (e.loaded / e.total) * 100;
      console.log(percentComplete + '% uploaded');
    }
  };
  //進度完成時
  xhr.onload = function() {
    if (this.status == 200) {
      var resp = JSON.parse(this.response);
      //resp就是在handle_file_upload.php頁面所準備的json陣列
      console.log('Server got:', resp);
      //這3行是把圖片顯示在畫面上
      var image = document.createElement('img');
      image.src = resp.dataUrl;
      document.body.appendChild(image);
    };
  };

  xhr.send(fd);
}, false);
</script>
<!--[if IE]>
<script src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script>CFInstall.check({mode: 'overlay'});</script>
<![endif]-->
</body>
</html>














留言

這個網誌中的熱門文章

jquery取得 input array 陣列

CI 使用ckeditor,ckfinder的替代品