Home > Web Front-end > JS Tutorial > Code to upload ajax files using FormData()

Code to upload ajax files using FormData()

不言
Release: 2018-08-02 13:44:37
Original
1716 people have browsed it

This article introduces to you the code about using FormData() to upload ajax files. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

HTML:

<form action="">
    
        <input type="file" id="file1" name="">
    
        <br>
    
        <input type="file" id="file2" name="">
    
        <br>
    
        <input type="button" value="保存">
    
    </form>
Copy after login

JS:

      $("input[type=&#39;button&#39;]").on(&#39;click&#39;, upfile);

        /**
         * [upfile 文件上传]
         * @return {[Object]} [成功回调]
         */
        function upfile() {
            
            var formData = new FormData();

            formData.append("接收字段1", document.getElementById(&#39;file1&#39;).files[0]);
            // console.log(document.getElementById(&#39;file1&#39;).files[0]);
            
            formData.append("接收字段2", document.getElementById(&#39;file2&#39;).files[0]);
            // console.log(document.getElementById(&#39;file2&#39;).files[0]);

            $.ajax({

                url: &#39;接口地址url&#39;,

                type: &#39;POST&#39;,

                data: formData, // 上传formdata封装的数据包

                dataType: &#39;JSON&#39;,

                cache: false, // 不缓存

                processData: false, // jQuery不要去处理发送的数据

                contentType: false, // jQuery不要去设置Content-Type请求头

                success: function(data) { // 成功回调

                    console.log(data);

                }

            });
        
        }
Copy after login

Successful effect:


Related recommendations:

The animation effect of loading before the ajax request is completed

How is the path object of nodeJs used to handle directories? (Code)

The above is the detailed content of Code to upload ajax files using FormData(). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template