简体   繁体   English

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

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

I am trying to upload a file using jQuery's $.ajax function but didn't get any output.我正在尝试使用 jQuery 的$.ajax函数上传文件,但没有得到任何输出。 Somebody please help me to solve this.有人请帮我解决这个问题。 I don't know if this script is correct.我不知道这个脚本是否正确。 My script is:我的脚本是:

$.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 从文件上传字段获取数据。

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

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 上的其他人。

AJAX doesnt support file uploading. AJAX 不支持文件上传。 There are plugins like ajaxfileupload which basically creates a hidden form and uploads your file dynamically.有像ajaxfileupload这样的插件,它基本上创建一个隐藏的表单并动态上传你的文件。

take a look here and read Oli's answer看看这里并阅读 Oli 的回答

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");
                });


            });

You can use either of the two plugins Jquery File Upload Plugins 1 or Jquery File Upload Plugins 2 and there's no errors on this script.您可以使用Jquery File Upload Plugins 1Jquery File Upload Plugins 2这两个插件中的任何一个,并且此脚本没有错误。

Hope it helps希望能帮助到你

Thanks, Rashid谢谢,拉希德

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

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

Simply use submit event on form to send the files and prevent default form action只需在表单上使用提交事件即可发送文件并防止默认表单操作

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

and get the file on the server side via并通过服务器端获取文件

$_FILES['inputName'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM