码迷,mamicode.com
首页 > Windows程序 > 详细

XMLHttpRequest file API

时间:2015-09-21 00:06:39      阅读:458      评论:0      收藏:0      [点我收藏+]

标签:

XMLHttpRequest file API

XMLHttpRequest file API

FormData

使用 FormData 不需要 setRequestHeader("content-type", "application/x-www-form-urlencoded");

<form id="tfrom">
  username: <input type="text" name="username"><br>
  age: <input type="text" name="age"><br>
  email: <input type="email" name="email"><br>
  <input type="button" value="ajax 发送" onclick="send();">
</form>
function send() {
    var fm = document.getElementById("tfrom");
    var fd = new FormData(fm);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "test.php", true);
    xhr.send(fd);      // 发送表单
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("debug").innerHTML = xhr.responseText;
        }
    }
}

// 也可以直接 new 一个, 然后 新建
function send() {
    var fd_test = FormData(fm);
    fd_test.append("username", "username_test");
    fd_test.append("email", "email_test");
    fd_test.append("age", "age_test");
    xhr.send(fd_test);
}

file API

<input type="file" name="file_name" onchange="select_file();">
<div id="debug"></div>
function select_file() {
    var file = document.getElementsByTagName("input")[0].files[0];
    var debug = document.getElementById("debug");
    var cont = "";
    cont += ‘文件名称: ‘ + file.name + "<br>";
    cont += ‘文件大小: ‘ + file.size + "<br>";
    debug.innerHTML = cont;
}

jquery file api

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 请求头
});

上传文件

<input type="file" name="file_name" onchange="select_file();">
<div id="debug"></div>
function select_file() {
    var myfile = document.getElementsByTagName("input")[0].files[0];
    var fd = new FormData();
    fd.append(‘myfile‘, myfile);

    var xhr = new XMLHttpRequest();
    xhr.open(‘post‘, ‘test.php‘, true);
    xhr.send(fd);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("debug").innerHTML = xhr.responseText;
        }
    }
}

test.php

<?php
echo ‘<pre>‘;
print_r($_FILES);
echo ‘</pre>‘;

从 FormData 中新建图片

function select_file() {
    var myfile = document.getElementsByTagName("input")[0].files[0];
    var fd = new FormData();
    fd.append(‘myfile‘, myfile);

    var xhr = new XMLHttpRequest();
    xhr.open(‘post‘, ‘test.php‘, true);
    xhr.send(fd);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("debug").innerHTML = xhr.responseText;
        }
    }

    // 显示图片
    var img = document.createElement(‘img‘);
    img.src = window.URL.createObjectURL(myfile);
    document.getElementsByTagName("body")[0].appendChild(img);
}

设置进度条

<input type="file" name="myfile" onchange="select_file();">
<div id="total" style="width: 500px; height: 50px; background: white; border: 1px solid green">
  <div id="loaded" style="width: 0%; height: 100%; background: green;"></div>
</div>
<div id="debug"></div>
function select_file() {
    var myfile = document.getElementsByTagName("input")[0].files[0];
    var fd = new FormData();
    fd.append(‘myfile‘, myfile);

    var xhr = new XMLHttpRequest();
    xhr.open(‘POST‘, ‘test.php‘, true);
    xhr.send(fd);

    xhr.upload.onprogress = function (event) {
        // console.log(event);
        if (event.lengthComputable) {
            // alert("loaded: " + event.loaded);
            // alert("total: " + event.total);    // fd.size

            var loaded = event.loaded;
            var total = event.total;
            var percent = 100 * loaded / total;
            document.getElementById("loaded").style.width = percent + "%";
        }
    }
    xhr.onload = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("debug").innerHTML = xhr.responseText;
        }
    }
}

大文件切割

function select_file() {
    const length = 10 * 1024 * 1024; // 10 M
    var start = 0;
    var end = start + length;
    var myfile = document.getElementsByTagName("input")[0].files[0];
    var total = myfile.size;

    var blob = new Blob();
    var fd = new FormData();

    while (start < total) {
        blob = myfile.slice(start, end);
        fd.append(‘file‘, blob);

        var percent = end/total * 100;
        document.getElementById("loaded").style.width = percent + ‘%‘;
        document.getElementById("loaded").innerHTML = percent + ‘%‘;

        var xhr = new XMLHttpRequest();
        xhr.open("post",  "test.php", false);  // 使用同步, 异步可能出现包顺序错误

        xhr.send(fd);

        start = end;
        end = start + length;
        if (end > total) {
            end = total;
        }
    }

}

test.php

<?php

$name = $_FILES[‘file‘][‘tmp_name‘];
$dest = ‘up/upload.txt‘;

if (!file_exists($dest)) {
    move_uploaded_file($name, $dest);
} else {
    file_put_contents($dest, file_get_contents($name), FILE_APPEND);
}

一些 XMLHttpRequest 2 的 API

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", progress, false);
xhr.addEventListener("load", complete, false);
xhr.addEventListener("error", failed, false);
xhr.addEventListener("abort", canceled, false);
xhr.open("POST", "test.php");
xhr.send(fd);

function progress(event) { .... }
function complete(event) { .... }
function failed  (event) { .... }
function canceled(event) { .... }

XMLHttpRequest 2 还支持括跨域

XMLHttpRequest file API

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4824714.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!