Rectangle 27 25

// grab your file object from a file input
$('#fileInput').change(function () {
  sendFile(this.files[0]);
});

// can also be from a drag-from-desktop drop
$('dropZone')[0].ondrop = function (e) {
  e.preventDefault();
  sendFile(e.dataTransfer.files[0]);
};

function sendFile(file) {
  $.ajax({
    type: 'post',
    url: '/targeturl?name=' + file.name,
    data: file,
    success: function () {
      // do something
    },
    xhrFields: {
      // add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
      onprogress: function (progress) {
        // calculate upload progress
        var percentage = Math.floor((progress.total / progress.totalSize) * 100);
        // log upload progress to console
        console.log('progress', percentage);
        if (percentage === 100) {
          console.log('DONE!');
        }
      }
    },
    processData: false,
    contentType: file.type
  });
}
file.name
file.fileName

it doesnot work on ie 9.0 and it lower version. please tell me how can implement same in those version of ie

javascript - How to upload file through Jquery/AJAX - Stack Overflow

javascript php jquery ajax file-upload
Rectangle 27 25

// grab your file object from a file input
$('#fileInput').change(function () {
  sendFile(this.files[0]);
});

// can also be from a drag-from-desktop drop
$('dropZone')[0].ondrop = function (e) {
  e.preventDefault();
  sendFile(e.dataTransfer.files[0]);
};

function sendFile(file) {
  $.ajax({
    type: 'post',
    url: '/targeturl?name=' + file.name,
    data: file,
    success: function () {
      // do something
    },
    xhrFields: {
      // add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
      onprogress: function (progress) {
        // calculate upload progress
        var percentage = Math.floor((progress.total / progress.totalSize) * 100);
        // log upload progress to console
        console.log('progress', percentage);
        if (percentage === 100) {
          console.log('DONE!');
        }
      }
    },
    processData: false,
    contentType: file.type
  });
}
file.name
file.fileName

it doesnot work on ie 9.0 and it lower version. please tell me how can implement same in those version of ie

javascript - How to upload file through Jquery/AJAX - Stack Overflow

javascript php jquery ajax file-upload
Rectangle 27 3

input type="file"
FormData
$.post()
$.ajaxSetup({processData:false,contentType:false});
$("input[type=file]").change(function() {    
  var data = new FormData(); data.append("file", this.files[0]);
  $.post("/path/to/server", data)
});
JSON

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

asp.net - How to upload file with JQuery to MVC VNext webserver? - Sta...

jquery asp.net asp.net-mvc asp.net-core-mvc asp.net-core
Rectangle 27 2

Add the input file tag your view.

<form asp-action="Index" asp-controller="Home">   
    <input type="file" id="logo" name="logo" />
    <input type="submit" id="btnSave" />
</form>

We will add some javascript to listen to the submit button event and send the data via ajax.

@section Scripts
{
    <script>
    $(function () {
        $("#btnSave").click(function (e) {
            e.preventDefault();

            var fdata = new FormData();

            var fileInput = $('#logo')[0];
            var file = fileInput.files[0];
            fdata.append("logo", file);

            $.ajax({
                type: 'post',
                url: "@Url.Action("SaveFile","Home")",
                data: fdata,
                processData: false, 
                contentType: false, 
            }).done(function (result) {
                // do something with the result now
                console.log(result);    
            });    
        });
    });
    </script>    
}

And you should have an an action method to accept the file posting

public class HomeController : Controller
{
    private readonly IHostingEnvironment hostingEnvironment;
    public HomeController(IHostingEnvironment environment)
    {
        hostingEnvironment = environment;
    }
    [HttpPost]
    public IActionResult Index(IFormFile logo)
    {
        if (logo != null)
        {
            var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
            var filePath = Path.Combine(uploads, GetUniqueFileName(logo.FileName));
            logo.CopyTo(new FileStream(filePath, FileMode.Create));

        }
        // to do  : Return something
        return RedirectToAction("Index","Home");
    }
    private string GetUniqueFileName(string fileName)
    {
        fileName = Path.GetFileName(fileName);
        return  Path.GetFileNameWithoutExtension(fileName)
                  + "_" 
                  + Guid.NewGuid().ToString().Substring(0, 4) 
                  + Path.GetExtension(fileName);
    }
}

This will save the file to uploads folder inside wwwwroot directory of your app with a random file name generated using Guids ( to prevent overwriting of files with same name)

asp.net - How to upload file with JQuery to MVC VNext webserver? - Sta...

jquery asp.net asp.net-mvc asp.net-core-mvc asp.net-core
Rectangle 27 8

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 7

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 7

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 7

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 7

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 7

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 7

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 7

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.

var $bar   = $('.ProgressBar');
$('.Form').ajaxForm({
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';
    $bar.width(percentVal);
  },

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';
    $bar.width(percentVal)
  },

  success: function(response) {
    // Response
  }
});

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 4

Easy, use a change trigger on your input Element and do an ajax-request inside:

$("#image_file_input").change(function() { 
    $.ajax({
        url: "my-target-url.php",
        type: "post",
        dataType: 'json',
        processData: false,
        contentType: false,
        data: {file: $("#image_file_input").val()},
        success: function(text) {
            if(text == "success") {
                alert("Your image was uploaded successfully");
            }
        },
        error: function() {
            alert("An error occured, please try again.");         
        }
    });   
});

Create a url or route and enter it at url: tag (domain/file.php) and then code serversided stuff:

function processFileUpload() {
    if(count($_FILES) > 0) {
        foreach($_FILES as $file) {
            //DO whatever you want with your file, save it in the db or stuff...
            //$file["name"];
            //$file["tmp_name"];
            //Insert here bla blubb
            echo "success";
        }
    }
    die();
}

got your point @steini... thanks a lot

You can't upload files using ajax alone without some sort of BLOB data, which can be created using the HTML5 file API.

I've tried this but it's not working. @steini

@up Just noticed one error in my script, $(#image_file_input).val() should be: $("#image_file_input").val() -> quotes were missing I edited the post. However If its still not working you should post some more output, errors, watch JavaScript console of your browser and try if the script on PHP side is called at all. Locate the error and provide me more information.

@Steini dataType: 'json' is generating conflicts with php answer also data: {file: $("#image_file_input").val()}, does not seem to correspond to PHP $_FILES that said, thank you a lot for the tips

javascript - How to upload file using jquery ajax and php (without cli...

javascript php jquery ajax file-upload
Rectangle 27 41

A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:

$(function() {
    $('#ifoftheform').ajaxForm(function(result) {
        alert('the form was successfully processed');
    });
});

The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...

This is no longer true. With a <input type='file' name='myfile'/> and the FormData() object, one can save a file using AJAX very simply. See Silver89's answer below.

@Rook777, that's of course true if the browser you are using supports the HTML5 File API. Have you tried this in IE how simple it is? Until HTML5 becomes a standard and supported by all browsers there will be plugins because you cannot upload files using AJAX.

You are correct. I am lucky enough to be in a development environment that does not support IE so I forgot to consider it. Yes, without HTML5 compatibility, this feature will not work. According to caniuse.com/xhr2, only IE 10+ supports this feature so far.

php - how to do file upload using jquery serialization - Stack Overflo...

php jquery ajax serialization file-upload
Rectangle 27 5

No no no, you should use a jQuery form plugin for async uploading files. You can't upload file with jQuery $.post method. The file will be uploaded with hidden iframe

Thanks mate! For now, i will just go with normal html form submit instead of jquery post. That way, it works for me!

PHP file-upload using jquery post - Stack Overflow

php jquery file-upload
Rectangle 27 5

No no no, you should use a jQuery form plugin for async uploading files. You can't upload file with jQuery $.post method. The file will be uploaded with hidden iframe

Thanks mate! For now, i will just go with normal html form submit instead of jquery post. That way, it works for me!

PHP file-upload using jquery post - Stack Overflow

php jquery file-upload
Rectangle 27 5

No no no, you should use a jQuery form plugin for async uploading files. You can't upload file with jQuery $.post method. The file will be uploaded with hidden iframe

Thanks mate! For now, i will just go with normal html form submit instead of jquery post. That way, it works for me!

PHP file-upload using jquery post - Stack Overflow

php jquery file-upload
Rectangle 27 2

Files cannot be uploaded directly through ajax. Instead of it you should use iframe or flash or jquery special plugins.

For example you can accomplish ajax file uploading through jquery forms plugin.

Public Class MessageController Inherits System.Web.Mvc.Controller

    Function SendNewMessage(ByVal file1 As HttpPostedFileBase) As JsonResult


        Dim fileName = Path.GetFileName(file1.FileName)
        Debug.Print(fileName)

        Return Nothing

    End Function

End Class

and this in your view:

<script type="text/javascript" >
    $(function () {
        var options = {
            beforeSubmit: function (formData, jqForm, options) { },  // pre-submit callback 
            success: function (responseText, statusText, xhr, form) { }   // post-submit callback 
        };
        // bind form using 'ajaxForm' 
        $('#uploadForm').ajaxForm(options);
    });
</script>

<form action="/Message/SendNewMessage" enctype="multipart/form-data" method="post" id="uploadForm" >
    <input type="file" name="file1" />
    <input type="submit" value="send" /> 
</form>

Is that a native jQuery method (ajaxForm) because I can't find any documentation anywhere. Do I need to use a plugin?

jquery - How to Upload Files in MVC - Stack Overflow

jquery asp.net-mvc vb.net asp.net-mvc-3
Rectangle 27 2

Files cannot be uploaded directly through ajax. Instead of it you should use iframe or flash or jquery special plugins.

For example you can accomplish ajax file uploading through jquery forms plugin.

Public Class MessageController Inherits System.Web.Mvc.Controller

    Function SendNewMessage(ByVal file1 As HttpPostedFileBase) As JsonResult


        Dim fileName = Path.GetFileName(file1.FileName)
        Debug.Print(fileName)

        Return Nothing

    End Function

End Class

and this in your view:

<script type="text/javascript" >
    $(function () {
        var options = {
            beforeSubmit: function (formData, jqForm, options) { },  // pre-submit callback 
            success: function (responseText, statusText, xhr, form) { }   // post-submit callback 
        };
        // bind form using 'ajaxForm' 
        $('#uploadForm').ajaxForm(options);
    });
</script>

<form action="/Message/SendNewMessage" enctype="multipart/form-data" method="post" id="uploadForm" >
    <input type="file" name="file1" />
    <input type="submit" value="send" /> 
</form>

Is that a native jQuery method (ajaxForm) because I can't find any documentation anywhere. Do I need to use a plugin?

jquery - How to Upload Files in MVC - Stack Overflow

jquery asp.net-mvc vb.net asp.net-mvc-3
Rectangle 27 2

Files cannot be uploaded directly through ajax. Instead of it you should use iframe or flash or jquery special plugins.

For example you can accomplish ajax file uploading through jquery forms plugin.

Public Class MessageController Inherits System.Web.Mvc.Controller

    Function SendNewMessage(ByVal file1 As HttpPostedFileBase) As JsonResult


        Dim fileName = Path.GetFileName(file1.FileName)
        Debug.Print(fileName)

        Return Nothing

    End Function

End Class

and this in your view:

<script type="text/javascript" >
    $(function () {
        var options = {
            beforeSubmit: function (formData, jqForm, options) { },  // pre-submit callback 
            success: function (responseText, statusText, xhr, form) { }   // post-submit callback 
        };
        // bind form using 'ajaxForm' 
        $('#uploadForm').ajaxForm(options);
    });
</script>

<form action="/Message/SendNewMessage" enctype="multipart/form-data" method="post" id="uploadForm" >
    <input type="file" name="file1" />
    <input type="submit" value="send" /> 
</form>

Is that a native jQuery method (ajaxForm) because I can't find any documentation anywhere. Do I need to use a plugin?

jquery - How to Upload Files in MVC - Stack Overflow

jquery asp.net-mvc vb.net asp.net-mvc-3