首页 > 技术文章 > Ajax 上传文件

liuxiaowei 2017-12-21 17:29 原文

通过传统的form表单提交的方式上传文件:

<style>
    form a {
        display: block;
        width: 90px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 5px;
        background-color: cornflowerblue;
        color: snow;
        margin-bottom: 10px;
        position: relative;
    }

    #image {
        width: 90px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        opacity: 0;
    }

    #image_view {
        display: none;
        height: 100px;
        margin-bottom: 10px;
    }
</style>

<form method="post" enctype="multipart/form-data">
    <a>上传图片<input type="file" id="image" name="image"></a>
    <img id="image_view" src="">
    <textarea id="desc" name="desc" rows="10" cols="50" placeholder="请输入图片描述..."></textarea>
    <button type="submit">发布</button>
</form>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
    $(function () {
        $('#image').on('change', function() {
            /* 原理: 把本地图片路径:"D:/image/..." 转为 "http://..." 格式路径进行显示图片 */
            var objUrl = $(this)[0].files[0];
            // 获得一个http格式的url路径: mozilla(firefox) || webkit or chrome
            var windowURL = window.URL || window.webkitURL;
            // createObjectURL创建一个指向该参数对象(图片)的URL
            var dataURL;
            dataURL = windowURL.createObjectURL(objUrl);
            $('#image_view').attr('src', dataURL).css('display', 'block');
        });
    });
</script>

传统的form表单提交会导致页面刷新,但是在有些情况下,我们不希望页面被刷新,这种时候我们使用Ajax的方式进行请求:

<style>
    form a {
        display: block;
        width: 90px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 5px;
        background-color: cornflowerblue;
        color: snow;
        margin-bottom: 10px;
        position: relative;
    }

    #image {
        width: 90px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        opacity: 0;
    }

    #image_view {
        display: none;
        height: 100px;
        margin-bottom: 10px;
    }
</style>

<form>
    <a>上传图片<input type="file" id="image" name="image"></a>
    <img id="image_view" src="">
    <textarea id="desc" name="desc" rows="10" cols="50" placeholder="请输入图片描述..."></textarea>
    <button type="button" id="publish">发布</button>
</form>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
    $(function () {
        $('#image').on('change', function () {
            /* 原理: 把本地图片路径:"D:/image/..." 转为 "http://..." 格式路径进行显示图片 */
            var objUrl = $(this)[0].files[0];
            // 获得一个http格式的url路径: mozilla(firefox) || webkit or chrome
            var windowURL = window.URL || window.webkitURL;
            // createObjectURL创建一个指向该参数对象(图片)的URL
            var dataURL;
            dataURL = windowURL.createObjectURL(objUrl);
            $('#image_view').attr('src', dataURL).css('display', 'block');
        });

        $('#publish').on('click', function () {
            var formData = new FormData($('form')[0]);
            // var formData = new FormData();
            // formData.append('image', $('#image')[0].files[0]);
            // formData.append('desc', $('#desc').val());
            $.ajax({
                url: '/index/',
                type: 'post',
                data: formData,
                contentType: false,
                processData: false,
                success: function (msg) {
                    // 提示信息
                }
            });
        });
    });
</script>

注:$('form').serialize()可以对form表单进行序列化,从而将form表单中的参数传递到服务端(创建以标准 URL 编码表示的文本字符串的方式)。只能传递一般的参数,上传文件的文件流是无法被序列化并传递的。

推荐阅读