如何使用带有 json 和 php 的 jquery 的 $.ajax 函数上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10492617/
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-24 22:19:35  来源:igfitidea点击:

How can I upload a file using jquery's $.ajax function with json and php

phpjqueryajaxjson

提问by JOE

I am trying to upload a file using jQuery's $.ajaxfunction but didn't get any output. Somebody please help me to solve this. I don't know if this script is correct. My script is:

我正在尝试使用 jQuery 的$.ajax函数上传文件,但没有得到任何输出。有人请帮我解决这个问题。我不知道这个脚本是否正确。我的脚本是:

$.ajax({
  url:'newsup.php',
  data: "",
  type: 'POST',
  contentType:'multipart/form-data',
  dataType: 'json',
  catche: 'false',

  success:function(data6)
  {
    $("#disp").removeClass().addClass((data6.error=== false)? 'success':'error').html(data6.msg).fadeIn('fast');
    //dele();
    if($("#disp").hasClass('success'))
    {
      alert("success");
      setTimeout("$('#disp').fadeOut('slow')",3000);            
    }
  },

  error:function(XMLHttpRequest,textStatus,errorThrown)
  {
    $("#disp").removeClass().addClass('error').html("There was an <strong>"+errorThrown+"</strong> error due to  <strong>"+textStatus+" condition").fadeIn('fast');
  }              

});

Also I need help getting data from file uploading field using jQuery.

此外,我需要帮助使用 jQuery 从文件上传字段获取数据。

采纳答案by killebytes

AJAX doesnt support file uploading. There are plugins like ajaxfileuploadwhich basically creates a hidden form and uploads your file dynamically.

AJAX 不支持文件上传。有像ajaxfileupload这样的插件,它基本上创建一个隐藏的表单并动态上传你的文件。

take a look hereand read Oli's answer

看看这里并阅读 Oli 的回答

回答by Oyeme

Please use plugin for this.
In my opinion this plugin is better solution for this.You don't need to remember all options etc.Just replace your 'ajax' to 'ajaxForm'.

请为此使用插件。
在我看来,这个插件是更好的解决方案。您不需要记住所有选项等。只需将您的“ajax”替换为“ajaxForm”。

Please read examples ,below
http://jquery.malsup.com/form/#ajaxForm

请阅读以下示例,
http://jquery.malsup.com/form/#ajaxForm

回答by Fred

This is how I've done it. Use the FormData object.

我就是这样做的。使用 FormData 对象。

Note: The odd syntax of the for statement is just setting "f" to the array[i] instance.

注意:for 语句的奇怪语法只是将 "f" 设置为 array[i] 实例。

        $("#submit").click(function () {
            var formData = new FormData();
            for (var i = 0, f; f = fileArray[i]; i++) {
                formData.append("opmlFile", f);
            }
            $.ajax({
                url: "/Documents/SaveFiles/" + @Model,
                type: "POST",
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            })
            .error(function (xhr, status, error) {
                $.notify(error, true);
            })
            .success(function (data, status, xhr) {
                $.notify("Success");
            });
        });

Unfortunately I don't recall which article I got this from, but it was someone else on Stack Overflow.

不幸的是,我不记得这是从哪篇文章中得到的,但它是 Stack Overflow 上的其他人。

回答by A-Sharabiani

I'm using this and it's working fine:

我正在使用它并且它工作正常:

  $('#btnUploadFile').on('click', function () {
                var data = new FormData();
                var files = $("#fileUpload").get(0).files;

                // Add the uploaded file content to the form data collection
                if (files.length > 0) {
                    data.append("upload", files[0]);
                }

                // Make Ajax request with the contentType = false, and procesDate = false
                var ajaxRequest = $.ajax({
                    type: "POST",
                    url: "/api/documents",
                    contentType: false,
                    processData: false,
                    data: data,

                    error: function (xhr, status, error) {
                        console.log(xhr);
                        console.log(status);
                        console.log(error);
                        console.log(data);
                    }
                });

                ajaxRequest.done(function (xhr, textStatus) {
                    $("#response").attr('class', "alert alert-success");
                    $("#response").html("File uploaded successfully");
                });


            });

回答by Rashid

You can use either of the two plugins Jquery File Upload Plugins 1or Jquery File Upload Plugins 2and there's no errors on this script.

您可以使用Jquery File Upload Plugins 1Jquery File Upload Plugins 2这两个插件中的任何一个,并且此脚本没有错误。

Hope it helps

希望能帮助到你

Thanks, Rashid

谢谢,拉希德

回答by lakhan_Ideavate

Ajax supports File upload using FormData Object, Also supports in all major browser except IE8/9 See below

Ajax 支持使用 FormData 对象上传文件,也支持除 IE8/9 之外的所有主流浏览器 见下文

https://developer.mozilla.org/en-US/docs/Web/API/FormData

https://developer.mozilla.org/en-US/docs/Web/API/FormData

回答by kmuenkel

Another option would be to base64 encode the file contents and send it as a string, decoding it at the back-end.

另一种选择是对文件内容进行 base64 编码并将其作为字符串发送,在后端对其进行解码。

回答by Kirill

Simply use submit event on form to send the files and prevent default form action

只需在表单上使用提交事件即可发送文件并防止默认表单操作

$('#form').submit(function(e) { return false; });

$('#form').submit(function(e) { return false; });

and get the file on the server side via

并通过服务器端获取文件

$_FILES['inputName'];