Javascript jQuery Ajax 文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2320069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:45:37  来源:igfitidea点击:

jQuery Ajax File Upload

javascriptjqueryajaxpostfile-upload

提问by Willy

Can I use the following jQuery code to perform file upload using POST method of an ajax request ?

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

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

If it is possible, do I need to fill datapart? Is it the correct way? I only POST the file to the server side.

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

I have been googling around, but what I found was a plugin while in my plan I do not want to use it. At least for the moment.

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

采纳答案by Adeel

File upload is notpossible through AJAX.
You can upload file, without refreshing page by using IFrame.
You can check further details here.

上传文件是不是有可能通过AJAX。
您可以上传文件,而无需使用IFrame.
您可以在此处查看更多详细信息。



UPDATE

更新

With XHR2, File upload through AJAX is supported. E.g. through FormDataobject, but unfortunately it is not supported by all/old browsers.

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

FormDatasupport starts from following desktop browsers versions.

FormData支持从以下桌面浏览器版本开始。

  • IE 10+
  • Firefox 4.0+
  • Chrome 7+
  • Safari 5+
  • Opera 12+
  • 浏览器 10+
  • 火狐 4.0+
  • 铬 7+
  • Safari 5+
  • 歌剧 12+

For more detail, see MDN link.

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

回答by Ziinloader

Iframes is no longer needed for uploading files through ajax. I've recently done it by myself. Check out these pages:

通过ajax上传文件不再需要iframes。我最近自己做的。查看这些页面:

Using HTML5 file uploads with AJAX and jQuery

通过 AJAX 和 jQuery 使用 HTML5 文件上传

http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface

http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface

Updated the answer and cleaned it up. Use the getSize function to check size or use getType function to check types. Added progressbar html and css code.

更新了答案并进行了清理。使用 getSize 函数检查大小或使用 getType 函数检查类型。添加了进度条 html 和 css 代码。

var Upload = function (file) {
    this.file = file;
};

Upload.prototype.getType = function() {
    return this.file.type;
};
Upload.prototype.getSize = function() {
    return this.file.size;
};
Upload.prototype.getName = function() {
    return this.file.name;
};
Upload.prototype.doUpload = function () {
    var that = this;
    var formData = new FormData();

    // add assoc key values, this will be posts values
    formData.append("file", this.file, this.getName());
    formData.append("upload_file", true);

    $.ajax({
        type: "POST",
        url: "script",
        xhr: function () {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                myXhr.upload.addEventListener('progress', that.progressHandling, false);
            }
            return myXhr;
        },
        success: function (data) {
            // your callback here
        },
        error: function (error) {
            // handle error
        },
        async: true,
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        timeout: 60000
    });
};

Upload.prototype.progressHandling = function (event) {
    var percent = 0;
    var position = event.loaded || event.position;
    var total = event.total;
    var progress_bar_id = "#progress-wrp";
    if (event.lengthComputable) {
        percent = Math.ceil(position / total * 100);
    }
    // update progressbars classes so it fits your code
    $(progress_bar_id + " .progress-bar").css("width", +percent + "%");
    $(progress_bar_id + " .status").text(percent + "%");
};

How to use the Upload class

如何使用上传类

//Change id to your id
$("#ingredient_file").on("change", function (e) {
    var file = $(this)[0].files[0];
    var upload = new Upload(file);

    // maby check size or type here with upload.getSize() and upload.getType()

    // execute upload
    upload.doUpload();
});

Progressbar html code

进度条html代码

<div id="progress-wrp">
    <div class="progress-bar"></div>
    <div class="status">0%</div>
</div>

Progressbar css code

进度条 css 代码

#progress-wrp {
  border: 1px solid #0099CC;
  padding: 1px;
  position: relative;
  height: 30px;
  border-radius: 3px;
  margin: 10px;
  text-align: left;
  background: #fff;
  box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
}

#progress-wrp .progress-bar {
  height: 100%;
  border-radius: 3px;
  background-color: #f39ac7;
  width: 0;
  box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
}

#progress-wrp .status {
  top: 3px;
  left: 50%;
  position: absolute;
  display: inline-block;
  color: #000000;
}

回答by pedrozopayares

Ajax post and upload file is possible. I'm using jQuery $.ajaxfunction to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

Ajax 发布和上传文件是可能的。我正在使用jQuery $.ajax函数来加载我的文件。我尝试使用 XHR 对象,但无法在服务器端使用 PHP 获得结果。

var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);

$.ajax({
       url : 'upload.php',
       type : 'POST',
       data : formData,
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType
       success : function(data) {
           console.log(data);
           alert(data);
       }
});

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize())existing form, and then attach the input file.

如您所见,您必须创建一个 FormData 对象,为空或来自(序列化? -$('#yourForm').serialize())现有表单,然后附加输入文件。

Here is more information: - How to upload a file using jQuery.ajax and FormData- Uploading files via jQuery, object FormData is provided and no file name, GET request

下面是详细信息: -如何上传使用jQuery.ajax和FORMDATA文件-上传文件通过jQuery,提供FORMDATA对象,并没有文件名,GET请求

For the PHP process you can use something like this:

对于 PHP 进程,您可以使用以下内容:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tama?o permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tama?o permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no terminó la acción de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningún archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}

回答by vickisys

Simple Upload Form

简单上传表格

 <script>
   //form Submit
   $("form").submit(function(evt){  
      evt.preventDefault();
      var formData = new FormData($(this)[0]);
   $.ajax({
       url: 'fileUpload',
       type: 'POST',
       data: formData,
       async: false,
       cache: false,
       contentType: false,
       enctype: 'multipart/form-data',
       processData: false,
       success: function (response) {
         alert(response);
       }
   });
   return false;
 });
</script>
<!--Upload Form-->
<form>
  <table>
    <tr>
      <td colspan="2">File Upload</td>
    </tr>
    <tr>
      <th>Select File </th>
      <td><input id="csv" name="csv" type="file" /></td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="submit" value="submit"/> 
      </td>
    </tr>
  </table>
</form>

回答by lee8oi

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.

我已经很晚了,但我一直在寻找基于 ajax 的图像上传解决方案,而我正在寻找的答案在这篇文章中有点分散。我确定的解决方案涉及 FormData 对象。我组装了我放在一起的代码的基本形式。您可以看到它演示了如何使用 fd.append() 向表单添加自定义字段以及如何在 ajax 请求完成时处理响应数据。

Upload html:

上传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>

In case you are working with php here's a way to handle the upload that includes making use of both of the custom fields demonstrated in the above html.

如果您正在使用 php,这里有一种处理上传的方法,包括使用上述 html 中演示的两个自定义字段。

Upload.php

上传.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";
}
?>

回答by koppor

An AJAX upload is indeed possible with XMLHttpRequest(). No iframes necessary. Upload progress can be shown.

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

For details see: Answer https://stackoverflow.com/a/4943774/873282to question jQuery Upload Progress and AJAX file upload.

详情参见:回答https://stackoverflow.com/a/4943774/873282质疑jQuery Upload Progress 和 AJAX file upload

回答by М.Б.

Here's how I got this working:

这是我如何工作的:

HTML

HTML

<input type="file" id="file">
<button id='process-file-button'>Process</button>

JS

JS

$('#process-file-button').on('click', function (e) {
    let files = new FormData(), // you can consider this as 'data bag'
        url = 'yourUrl';

    files.append('fileName', $('#file')[0].files[0]); // append selected file to the bag named 'file'

    $.ajax({
        type: 'post',
        url: url,
        processData: false,
        contentType: false,
        data: files,
        success: function (response) {
            console.log(response);
        },
        error: function (err) {
            console.log(err);
        }
    });
});

PHP

PHP

if (isset($_FILES) && !empty($_FILES)) {
    $file = $_FILES['fileName'];
    $name = $file['name'];
    $path = $file['tmp_name'];


    // process your file

}

回答by lgersman

In case you want to do it like that:

如果你想这样做:

$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
    if( progressEvent.lengthComputable) {
        var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
        if( upload) {
            console.log( percent + ' uploaded');
        } else {
            console.log( percent + ' downloaded');
        }
    }
})
.done( function() {
    console.log( 'Finished upload');                    
});

than

https://github.com/lgersman/jquery.orangevolt-ampere/blob/master/src/jquery.upload.js

https://github.com/lgersman/jquery.orangevolt-ampere/blob/master/src/jquery.upload.js

might be your solution.

可能是你的解决方案。

回答by Gvice

$("#submit_car").click( function() {
  var formData = new FormData($('#car_cost_form')[0]);
$.ajax({
       url: 'car_costs.php',
       data: formData,
       async: false,
       contentType: false,
       processData: false,
       cache: false,
       type: 'POST',
       success: function(data)
       {
       },
     })    return false;    
});

edit: Note contentype and process data You can simply use this to upload files via Ajax...... submit input cannot be outside form element :)

编辑:注意内容类型和处理数据您可以简单地使用它通过 Ajax 上传文件......提交输入不能在表单元素之外:)

回答by Manki

  • Use a hidden iframe and set your form's target to that iframe's name. This way, when the form is submitted, only the iframe will be refreshed.
  • Have an event handler registered for the iframe's load event to parse the response.
  • 使用隐藏的 iframe 并将表单的目标设置为该 iframe 的名称。这样,当表单提交时,只会刷新 iframe。
  • 为 iframe 的 load 事件注册一个事件处理程序来解析响应。

More details on my blog post: http://blog.manki.in/2011/08/ajax-fie-upload.html.

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