[Solved]-Uploading both data and files in FormData using Ajax MVC


ASP.NET offers various approaches for file uploads, allowing you to choose the one that best fits your requirements. 

Whether you need to upload a few files or multiple files simultaneously, handle small or very large files, send entire folders, upload a simple image, or preprocess pictures, there's an appropriate method available.

In this article, we explore different file upload methods in ASP.NET MVC, such as uploading files and JSON data in the same POST request using jQuery AJAX, and discuss their use. However, let's first understand how the file upload input control works in general.

If you prefer to achieve the same task without using AJAX, you can refer to the articles below.

The file upload process is quite simple. It involves two main components: the client and server sides, which communicate with each other via HTTP requests and responses.

 

  1. Now Add a controller “Home” in the Project and also add an action method in it.
  2. Right Click in the Action Method and add a View 
We are going to use FormData to accomplish our task. FormData provides the best way to create a set of key-value pairs representing form fields in our HTML page and their values. 
We can easily send these values using the XMLHttpRequest.send() method.

Now, let’s write code in the controller to handle file uploads.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace UploadingFileMvc.Controllers
{

public class FilesInoformation
    {
public string filename { get; set; }
public string filepath { get; set; }
    }
public class FileUploadController : Controller
    {
// GET: FileUpload
// GET: Home
public ActionResult Index()
        {
//getting the list of file uploaded 
            DirectoryInfo directory = new DirectoryInfo(Server.MapPath(@"~\PdfFiles"));
var files = directory.GetFiles().ToList();
            List<FilesInoformation> model = new List<FilesInoformation>();
foreach (var file in files)
            {
                model.Add(new FilesInoformation { filename = file.Name, filepath = "/PdfFiles/" + file.Name });
            }
return View(model);
        }

//For Uploading Multiple files at once
        [HttpPost]
public ActionResult UploadMultiplePdfFiles()
        {
//getting form data
string username = Request.Form["Username"];
string userId = Request.Form["UserId"];
if (Request.Files.Count > 0)            // Checking if  Request object  has file
            {
try
                {
                    HttpFileCollectionBase files = Request.Files;
//in case if you want upload the multiple pdf files
for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFileBase file = files[i];
string fname = file.FileName;
// Get the complete folder path and store the file inside it.  
                        fname = Path.Combine(Server.MapPath("~/PdfFiles/"), fname);
                        file.SaveAs(fname);
                    }
return Json("Pdf Uplaoded Successfully!");
                }
catch (Exception ex)
                {
return Json(ex.Message);
                }
            }
else
            {
return Json("No files selected.");
            }
        }
    }
}


FileUploadController, which handles file uploads. 

  • The FilesInformation class is defined to hold information about uploaded files, such as filename and filepath.
  • The Index action method is responsible for displaying the list of files uploaded. It retrieves the list of files from the specified directory (PdfFiles) and constructs a list of FilesInformation objects, which is then passed to the view for rendering.
  • The UploadMultiplePdfFiles action method handles the HTTP POST request for uploading multiple PDF files. It retrieves form data (username and userId) and checks if any files are uploaded.
  • If files are uploaded, it iterates through each file in the Request.Files collection, saves each file to the specified directory (PdfFiles), and returns a JSON response indicating success.
  • If no files are uploaded, it returns a JSON response indicating that no files were selected.

Overall, FileUploadController controller provides functionality for displaying the list of uploaded files and handling the upload of multiple PDF files. It ensures proper handling of form data and file uploads while handling exceptions appropriately.

View Html Code

 

@model  IEnumerable<UploadingFileMvc.Controllers.FilesInoformation>

@{
    ViewBag.Title = "";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
@using (Html.BeginForm("UploadPdf", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Upload a Pdf file By Ajax</legend>
        <div class="editor-field">
            @Html.TextBox("pdffile", "", new { type = "file", accept = "application/pdf" })
        </div>
        <br />
        <br />
        <div class="editor-field">
            <input type="button" id="btnfileUpload" value="Upload Pdf" />
        </div>
        <div class="row">
            <h3>Uploaded Filles</h3>
            <table class="table">
                <thead>
                    <tr>
                        <th>FileName</th>
                        <th>Action</th>
                    </tr>
                </thead>
                @if (Model != null)
                {
foreach (var file in Model)
                    {
                        <tr>
                            <td>@file.filename</td>
                            <td><a href="@file.filepath">View Pdf</a></td>
                        </tr>
                    }
                }
            </table>
        </div>
    </fieldset>
    <script>

        $(document).ready(function(){
            $('#btnfileUpload').click(function () {
if (window.FormData !== undefined) {
var fileUpload = $("#pdffile").get(0);
var files = fileUpload.files;
var fileData = new FormData();
                    fileData.append('Username', 'testuser');
                    fileData.append('UserId', '1');
for (var i = 0; i < files.length; i++) {
                        fileData.append(files[i].name, files[i]);
                    }
                    $.ajax({
                        url: '/FileUpload/UploadMultiplePdfFiles',
                        type: "POST",
                        contentType: false,
                        processData: false,
                        data: fileData,
                        success: function (result) {
                            alert(result);
                            window.location.reload();
                        },
                        error: function (err) {
                            alert(err.statusText);
                        }
                    });
                } else {
                    alert("Your browser doesn support FormData");
                }
            });
        });
    </script>
}

 Razor view page that is used to display a form for uploading PDF files and listing the uploaded files. 

The form is submitted to the UploadMultiplePdfFiles action of the FileUpload controller using the POST method and multipart/form-data enctype.

Inside the form, there is an input field of type file for selecting PDF files. It also includes a button with the id btnfileUpload to trigger the file upload process.

The view renders a table to display the list of uploaded files, with columns for filename and a link to view the PDF file.

The JavaScript code inside the <script> tag handles the file upload process using AJAX. It listens for the click event on the upload button (#btnfileUpload).

When the button is clicked, it checks if the browser supports the FormData object. If supported, it creates a new FormData object and appends the selected files along with form data (username and userId).

It sends an AJAX request to the UploadMultiplePdfFiles action with the file data. It sets contentType and processData options to false to ensure proper handling of multipart/form-data.

Upon successful upload, it displays an alert with the result and reloads the page to display the updated list of uploaded files. If there's an error, it displays an alert with the error message.

Uploading both data and files in one form using Ajax MVC

If you have any questions related to the post please comment.

Share this article to Facebook, Twitter, Reddit, and other social media platform to help developers who face the same issue.