简体   繁体   中英

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. 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.

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'.

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

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

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

        $("#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.

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

take a look here and read Oli's answer

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.

Hope it helps

Thanks, Rashid

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

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'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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