开发者社区> 问答> 正文

jquery里面用 $.ajax post文件

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

展开
收起
小旋风柴进 2016-05-30 08:52:21 3201 0
1 条回答
写回答
取消 提交回答
  • 用 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>
    2019-07-17 19:18:56
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载