美文网首页
文件上传的几种方式

文件上传的几种方式

作者: 回不去的那些时光 | 来源:发表于2018-12-20 11:20 被阅读24次

    方式一:form表单文件上传

    <form action="http://localhost:8081/images" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload" />
     </form>
    
    • 图片上传的请求方式必须为post
    • enctype="multipart/form-data" 参数不能少

    方式二:借助form的ajax文件上传

    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" name="file" id="file">
        <input type="button" value="Upload" id="upload"/>
    </form>
    
    <script src="jquery.min.js"></script>
    <script>
        $(function () {
            $('#upload').click(function() {
                $.ajax({
                    url: "http://localhost:8081/images",
                    type: "post",
                    data: new FormData($('#uploadForm')[0]),
                    cache: false,
                    processData:false,
                    contentType:false,
                    success: function(res) {
                        console.log(res)
                    },
                    error: function(err) {
                        console.log(err)    
                    }
                })
            })
        })
    </script>
    
    • processData设置为false。因为data值是FormData对象,不需要对数据做处理。
    • <form>标签添加enctype="multipart/form-data"属性。
    • cache设置为false,上传文件不需要缓存。
    • contentType设置为false。因为是由<form>表单构造的FormData对象,且已经声明了属性enctype="multipart/form-data",所以这里设置为false。

    方式三:不借助form的ajax文件上传

    <input type="file" name="file" id="file">
    <input type="button" value="Upload" id="upload"/>
    
    <script src="jquery.min.js"></script>
    <script>
      $(function () {
          $('#upload').click(function() {
                let file = $("#file")[0].files[0];
                //创建formdata对象
                let formData = new FormData();
                formData.append("file",file);
                $.ajax({
                    url: "http://localhost:8081/images",
                    type: "post",
                    data: formData,
                    cache: false,
                    processData:false,
                    contentType:false,
                    // headers: { 'Content-Type': 'multipart/form-data' },
                    success: function(res) {
                        console.log(res)
                    },
                    error: function(err) {
                        console.log(err)    
                    }
                })
            })
        })
    </script>
    
    • append()的第二个参数应是文件对象,即$('#file')[0].files[0]。
    • contentType也要设置为‘false’。
    • 从代码$('#file')[0].files[0]中可以看到一个<input type="file">标签能够上传多个文件, 只需要在<input type="file">里添加multiple或multiple="multiple"属性。

    文章后两种方式借鉴了 https://my.oschina.net/jgy/blog/743670

    相关文章

      网友评论

          本文标题:文件上传的几种方式

          本文链接:https://www.haomeiwen.com/subject/azdghqtx.html