jquery里面用 $.ajax post文件-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

jquery里面用 $.ajax post文件

小旋风柴进 2016-05-30 08:52:21 1304

怎么在jquery里面用 $.ajax 上传文件。

前端开发 JavaScript
分享到
取消 提交回答
全部回答(1)
  • 小旋风柴进
    2019-07-17 19:18:56

    用 FormData,一个例子:

    I'm pretty late for this but I was looking for an ajax based image uploading solution and the answer I was looking for was kinda scattered throughout this post. The solution I settled on involved the FormData object. I assembled a basic form of the code I put together. You can see it demonstrates how to add a custom field to the form with fd.append() as well as how to handle response data when the ajax request is done.

    Upload html:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Image Upload Form</title>
        <script src="//code.jquery.com/jquery-1.9.1.js"></script>
        <script type="text/javascript">
            function submitForm() {
                console.log("submit event");
                var fd = new FormData(document.getElementById("fileinfo"));
                fd.append("label", "WEBUPLOAD");
                $.ajax({
                  url: "upload.php",
                  type: "POST",
                  data: fd,
                  enctype: 'multipart/form-data',
                  processData: false,  // tell jQuery not to process the data
                  contentType: false   // tell jQuery not to set contentType
                }).done(function( data ) {
                    console.log("PHP Output:");
                    console.log( data );
                });
                return false;
            }
        </script>
    </head>
    
    <body>
        <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
            <label>Select a file:</label><br>
            <input type="file" name="file" required />
            <input type="submit" value="Upload" />
        </form>
        <div id="output"></div>
    </body>
    0 0
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题
推荐课程