AJAX資料互動及檔案上傳功能

weixin_33968104發表於2018-09-22

一、檔案下載
正常情況下,要檔案壓縮

<a href = "test.zip">點選就下載</a>

沒有壓縮的話會直接開啟

<a href = "test.txt">點選就下載</a>
let btn = document.querySelector("input");
btn.onclick = function(){
  let link = document.createElement("a");
  link.download = "檔案.txt";
  link.href = "test.txt";
  link.click();
}
//演示檔案操作功能
const str = "hello";
downLoadFile("test.doc", str);
function downLoadFile(fileName, content){
  const blob = new Blob([content], {type:"application/msword"});
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.download = fileName;
  link.href = url;
  link.click();
} 

二、請求php資源
跨域請求都是後端解決的,前端只是通過各種方式去發起請求

let xhr = new XMLHttpRequest();
xhr.onload = function(){
  if(xhr.readyState == 4 && xhr.status == 200){
    console.log(xhr.response);
  }
}
xhr.open("get", "data.php", true);
xhr.send();
<?php

header('Access-Control-Allow-Origin:*');

$arr = array(
  array(
    'id' => 1,
    'name' => '張三',
    'age'=>20
  )
);

echo json_encode($arr);

三、jsonp
本質就是返回函式的呼叫

function myData(data){
  console.log(data);
}
createJsonp();
function createJsonp(){
  let s = document.createElement("script");
  s.src = "jsonp.php?callback=myData";
  document.body.appendChild(s);
}
<?php
  header('Access-Control-Allow-Origin:*');

  $jsonp = $_GET['callback'];
  $arr = array('張三', 18);
  echo $jsonp.'('.json_encode($arr).')';

四、upload

let ipt = document.querySelector("input");
let div = document.querySelector("div");
let p = document.querySelector("p");
ipt.addEventListener('change', function(){
  //console.log(this.value);//只是字串,不代表路徑,表示value
  if(this.value){
    let oFile = this.files[0];
    uploadFiles(oFile);
    this.value = "";
  }
})
div.addEventListener("dragover", function(e){
  e.preventDefault();
  e.stopPropagation();
})
div.addEventListener("drop", function(e){
  e.preventDefault();
  e.stopPropagation();
  let oFile = e.dataTransfer.files[0];
  uploadFiles(oFile);
})
//既可以通過表單控制元件,又可以通過H5拖拽的實現圖片預覽
function uploadFiles(oFile){
  let blob = new Blob([oFile]);  //第一個引數一定是一個陣列,第二個是mime型別
  let url = window.URL.createObjectURL(blob);
  let img = new Image();
  img.width = 300;
  img.height = 150;
  img.src = url;
  img.onload = function(){
    document.body.appendChild(this);
  }

  //檔案上傳功能,需要後端配置,前端只是傳送資料
  const xhr = new XMLHttpRequest();
  xhr.onload = function(){

  }
  xhr.upload.onprogress = function(e){
    let scale = e.loaded/e.total;
    p.style.width = scale*window.innerWidth + "px";
  }
  const oFD = new FormData();
  oFD.append("file", oFile);
  xhr.open("post", "upload.php", true);
  xhr.send(oFD);
}
<?php
$myFile = $_FILES['file'];
$myName = $myFile['name'];
$myPath = 'upload'.$myName;

move_uploaded_file($myFile['tmp_name'], $myPath);

相關文章