ajax上传图片与预览图片demo

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax Upload demo</title>
</head>
<body>

<form id="uploadForm" enctype="multipart/form-data">
    <input id="file" type="file" name="file"/>
    <button id="upload" type="button">upload</button>
</form>
<img id="pre" src="#" width="800" height="600"/>
<button id="show" >show</button>
</body>
<script src="http://cdn.bootcss.com/jquery/3.1.0/jquery.js"></script>
<script>
    $('#upload').click(upload);
    $('#file').change(function(){
                var reader = new FileReader();
        reader.readAsDataURL($('#file')[0].files[0]);
        reader.onload = function (e) {
            $('#pre').attr('src', this.result)
        }
    })
    function upload() {
        var form = new FormData();
        form.append("file", $('#file')[0].files[0]);
        form.append("name", "jdlsajdlkas");
        form.append("order", "1");

        var settings = {
            "async": true,
            "crossDomain": true,
            "url": "/attachments/",
            "method": "POST",
            "processData": false,
            "contentType": false,
            "mimeType": "multipart/form-data",
            "data": form
        }

        $.ajax(settings).done(function (response) {
            console.log(response);
        });
    }
</script>
</html>
    原文作者:Prasanta
    原文地址: https://segmentfault.com/a/1190000006757806
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞