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

开发者社区> 问答> 正文

jquery里面用 $.ajax post文件

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

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

前端开发 JavaScript
取消 提交回答
  • 小旋风柴进
    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>
        <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");
                  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;
        <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" />
        <div id="output"></div>
    0 0
+ 订阅