jQuery Ajax文件上传

JavaScript

神乐宝儿小小

2020-03-11

我可以使用以下jQuery代码使用ajax请求的POST方法执行文件上传吗?

$.ajax({
    type: "POST",
    timeout: 50000,
    url: url,
    data: dataString,
    success: function (data) {
        alert('success');
        return false;
    }
});

如果可能,我是否需要填写data部分?这是正确的方法吗?我只将文件发布到服务器端。

我一直在搜索,但是我发现是一个插件,而在我的计划中我不想使用它。至少目前是这样。

第601篇《jQuery Ajax文件上传》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
GO蛋蛋 2020.03.11

Here was an idea i was thinking of:

Have an iframe on page and have a referencer.

Have a form in which you move the INPUT:File element to.

Form:  A processing page AND a target of the FRAME.

The result will post to the frame, and then you can just send the fetched data up a level to the image tag you want with something like:

data:image/png;base64,asdfasdfasdfasdfa

and the page loads.

I believe it works for me, and depending you might be able to do something like:

.aftersubmit(function(){
    stopPropigation()// or some other code which would prevent a refresh.
});
JinJin乐逆天 2020.03.11

to upload a file which is submitted by user as a part of form using jquery please follow the below code :

var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);

Then send the form data object to server.

We can also append a File or Blob directly to the FormData object.

data.append("myfile", myBlob, "filename.txt");
小胖逆天 2020.03.11

我已经用简单的代码处理了这些。您可以从此处下载有效的演示

对于您的情况,这些很有可能。我将逐步指导您如何使用AJAX jquery将文件上传到服务器。

首先,让我们创建一个HTML文件,以添加以下表单文件元素,如下所示。

<form action="" id="formContent" method="post" enctype="multipart/form-data" >
         <input  type="file" name="file"  required id="upload">
         <button class="submitI" >Upload Image</button> 
</form>

其次,创建一个jquery.js文件,并添加以下代码来处理我们向服务器提交的文件

    $("#formContent").submit(function(e){
        e.preventDefault();

    var formdata = new FormData(this);

        $.ajax({
            url: "ajax_upload_image.php",
            type: "POST",
            data: formdata,
            mimeTypes:"multipart/form-data",
            contentType: false,
            cache: false,
            processData: false,
            success: function(){
                alert("file successfully submitted");
            },error: function(){
                alert("okey");
            }
         });
      });
    });

到此为止。查看更多

阿飞Sam猪猪 2020.03.11
  • 使用隐藏的iframe,然后将表单目标设置为该iframe的名称。这样,提交表单时,仅会刷新iframe。
  • 为iframe的load事件注册一个事件处理程序,以解析响应。

有关我的博客文章的更多详细信息:http : //blog.manki.in/2011/08/ajax-fie-upload.html

卡卡西Davaid 2020.03.11

我为此很晚,但是我正在寻找一个基于Ajax的图像上传解决方案,而我一直在寻找的答案在整个帖子中都有些分散。我确定的解决方案涉及FormData对象。我组装了代码的基本形式。您可以看到它演示了如何使用fd.append()向表单添加自定义字段,以及如何在ajax请求完成后处理响应数据。

上载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,
              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>
</html>

如果您使用的是php,这是一种处理上传的方法,其中包括利用上面html中演示的两个自定义字段。

Upload.php

<?php
if ($_POST["label"]) {
    $label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {
        $filename = $label.$_FILES["file"]["name"];
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("uploads/" . $filename)) {
            echo $filename . " already exists. ";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"],
            "uploads/" . $filename);
            echo "Stored in: " . "uploads/" . $filename;
        }
    }
} else {
    echo "Invalid file";
}
?>
乐西门 2020.03.11

使用确实可以上传AJAX XMLHttpRequest()无需iframe。可以显示上传进度。

有关详细信息,请参见:回答https://stackoverflow.com/a/4943774/873282以质疑jQuery Upload Progress和AJAX文件上传

猿Near 2020.03.11

文件上传是不是可以通过Ajax。您可以使用IFrame上传文件,而无需刷新页面。您可以在此处查看更多详细信息

更新:

使用XHR2,支持通过AJAX上传文件。例如,通过FormData对象,但是不幸的是,所有/旧的浏览器都不支持它。

FormData支持从以下桌面浏览器版本开始。IE 10以上版本,Firefox 4.0以上版本,Chrome 7以上版本,Safari 5以上版本,Opera 12以上版本

有关更多详细信息,请参见MDN链接。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android