, , ,

How to upload file using Javascript – C# MVC

Posted by

Certainly! Here’s an example of how you can upload a file from a web page using JavaScript and then retrieve it on the server-side using C#:

JavaScript (Client-side):

function uploadFile() {
  var fileInput = document.getElementById('fileInput');
  var file = fileInput.files[0];

  var formData = new FormData();
  formData.append('file', file);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/YourController/UploadFile'); // Replace with your controller and action method names
  xhr.onload = function() {
    if (xhr.status === 200) {
      console.log('File uploaded successfully!');
    } else {
      console.log('Error occurred while uploading the file.');

HTML (Client-side):

<input type="file" id="fileInput" />
<button onclick="uploadFile()">Upload</button>

C# (Server-side):

public class YourController : Controller
    // Other action methods...

    public ActionResult UploadFile()
            var file = Request.Files[0];
            if (file != null && file.ContentLength > 0)
                var fileName = Path.GetFileName(file.FileName);
                var filePath = Path.Combine(Server.MapPath("~/Uploads"), fileName);

                // Process the uploaded file as needed

                return Json(new { success = true });
        catch (Exception ex)
            // Handle any exceptions that occurred during file upload or processing

        return Json(new { success = false });

Make sure to replace “YourController” with the actual name of your controller and customize the file upload and processing logic as per your requirements.

In the HTML, the fileInput element allows users to select a file, and the uploadFile function is called when the “Upload” button is clicked. The JavaScript code creates a FormData object, appends the selected file to it, and sends it as an AJAX request to the server.

On the server-side, the UploadFile action method receives the file using the Request.Files collection. It saves the file to a specified location (e.g., “~/Uploads”) and performs any additional processing required.

Note that you may need to adjust the file storage path and handle error conditions appropriately in your application.

Remember to handle exceptions, perform necessary security validations, and implement file size restrictions or other validation checks as required by your application.