billfeller.github.io icon indicating copy to clipboard operation
billfeller.github.io copied to clipboard

文件上传方法

Open billfeller opened this issue 6 years ago • 0 comments

  1. 传统表单提交:通过表单input="file"实现文件上传,用户提交表单后,页面刷新,跳转到表单action属性指定的网址,属于同步上传方式。优点:实现简单;缺点:需要刷新页面,体验较差。
    <form 
        method="post" 
        enctype="multipart/form-data" 
        action="/upload/form" 
        target="_blank">
        <input type="file" name="upload">
        <input type="submit" value="submit">
    </form>
  1. 基于iframe的异步上传:将form表单的target属性指向页面中隐藏的iframe,从而提交表单是,服务器将结果返回到iframe窗口,从而当前页面不会跳转。在同源iframe中调用父级窗口的方法实现将上传结果同步到父级页面中。优点:无刷新,兼容性强;缺点:iframe实现不够优雅。
    <!-- iframe -->
    <!--
        // /upload/iframe response
        <script>parent.callback("success")</script>
    -->
    <form 
        method="post" 
        enctype="multipart/form-data" 
        action="/upload/iframe" 
        target="hidden_frame">
        <input type="file" name="upload">
        <input type="submit" value="submit">
    </form>

    <!-- 隐藏的iframe -->
    <iframe id="hidden_frame" name="hidden_frame" style="display: none;"></iframe>
    <div id="msg"></div>

    <script>
        function callback(result) {
            document.getElementById("msg").innerHTML = "<span>" + result + "</span>";
        }
    </script>
  1. 基于HTML5 XMLHTTPRequest 2.0,利用FormData实现异步上传。优点:实现简单,原生支持;缺点:需要现代浏览器支持XMLHTTPRequest 2.0。
    <!-- ajax -->
    <form 
        method="post" 
        enctype="multipart/form-data" 
        id="uploadform">
        <input type="file" name="upload">
        <input type="button" id="upload" value="上传">
    </form>
    <div id="msg"></div>
    <script>
        $('#upload').click(function () {
            // 创建formdata对象
            var formData = new FormData($('#uploadform')[0]);
            $.ajax({
                url: '/upload/ajax',
                type: 'post',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                    $('#msg').text('success');
                },
                error: function () {
                    $('#msg').text('error');
                }
            });
        });
    </script>

参考阅读:https://github.com/chenjunxyf/NodeDemos/tree/master/fileupload

billfeller avatar Mar 17 '18 07:03 billfeller