[javascript]multipart/form-data上传格式表单自定义创建

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<input type="file" id="file">
<button id="trigger">trigger</button>
<script type="text/javascript">
    var file = document.getElementById("file");
    var trigger = document.getElementById("trigger");

    trigger.addEventListener("click", function(e){
        var reader = new FileReader();
        reader.readAsDataURL(file.files[0].slice());
        reader.addEventListener("loadend", function(e){
            req = new XMLHttpRequest();
            req.overrideMimeType("text/plain");
            req.addEventListener("load", function(e){
                var img = document.createElement("img");
                img.src = e.target.response;
                document.body.appendChild(img);
            }, false);
            req.open("post", "./tmp_50.php");
            var sBoundary = "---------------------------" + Date.now().toString(16);
            req.setRequestHeader("Upgrade-Insecure-Requests", "1");
            req.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
            var data = new Blob(["--" + sBoundary + "\r\n" + "Content-Disposition: form-data; name=\"payload\"; filename=\"payload.data\"" + "\r\n" + "Content-Type: application/octet-stream" + "\r\n" + "\r\n", reader.result, "\r\n" + "--" + sBoundary + "--" + "\r\n"], {type : 'application/octet-stream'});

            req.send(data);
        });
    }, false);

</script>
</body>
</html>

PHP:

<?php
header("Content-Type: image/jpeg");
//move_uploaded_file($_FILES['payload']['tmp_name'], './files/tmp_50.jpg');
echo file_get_contents($_FILES['payload']['tmp_name']);
?>

 

posted @ 2018-03-14 11:46  yiyide266  阅读(2012)  评论(0编辑  收藏  举报