"Enhancing user experience with JQuery and MVC4 through efficient multiple file uploads

Currently, I'm facing a challenge in uploading multiple files alongside regular form data. While I had successfully implemented this functionality in PHP before, I am now attempting to achieve the same in ASP.NET MVC4 using C#. Below is the HTML form I have:

<form action="/controller/actionane" name="applicationform" class="upload-form" method="post" onsubmit="return false;" enctype="multipart/form-data" id="userform"> 
        <input class="form-control" type="file" class="upload-file" data-max-size="12582912" multiple="multiple" name="attachment[]" value="documents">
        <input class="btn btn-success" type="submit" name="submit" onclick="formSubmit()" />
    </form>

Included below is my JavaScript code utilizing jquery-1.11.1:

function formSubmit() {
    var form = $("form[name='applicationform']");
    var data = new FormData(form[0]);
    $.ajax(
        {
            method: "POST",
            url: form.attr("action"),
            processData: false, // Don't process the files
            contentType: false, cache: false, async: false,
            data: data,
            success: function (data) {
                alert(data);
            }
        });
}

Here's a glimpse of how my controller is structured:

[HttpPost]
public JsonResult submitApplication(HttpPostedFileBase[] attachment) 
{
                string fil= "";
                foreach (HttpPostedFileBase file in attachment)
                {
                    /*Geting the file name*/
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    fil += filename;
                    /*Saving the file in server folder*/
                    file.SaveAs(Server.MapPath("~/Images/" + filename));
                    string filepathtosave = "Images/" + filename;
                    /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
                }

                    return this.Json(fil,JsonRequestBehavior.AllowGet);
}

Unfortunately, I'm encountering an issue where the files are not being passed to the parameter, resulting in an Object reference null exception. What steps should I take to rectify this and ensure everything runs smoothly?

Answer №1

Give this a shot:

Code for the Client Side:

<html>
<head>
<title>File Upload Example</title>
<script src="~/Scripts/jquery-2.1.0.intellisense.js"></script>
<script src="~/Scripts/jquery-2.1.0.js"></script>
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<script>
$(document).ready(function () {
    $("#Upload").click(function () {
        var formData = new FormData();
        var totalFiles = document.getElementById("FileUpload").files.length;
        for (var i = 0; i < totalFiles; i++)
        {
            var file = document.getElementById("FileUpload").files[i];
           
            formData.append("FileUpload", file);
         }
          $.ajax({
              type: "POST",
              url: '/Home/Upload',
              data: formData,
               dataType: 'json',
                contentType: false,
                 processData: false,
                  success: function (response) {
                      alert('Success!');
                   },
                    error: function (error) {
                        alert("Failed");
                     }
             });
      });
 });

</script>
</head>
<body>
<input type="file" id="FileUpload" multiple />
<input type="button" id="Upload" value="Upload" />
</body>
</html>

Code for the Server Side:

On the server side....

public class HomeController : Controller
{
   [HttpPost]
   public void Upload( )
   {
     for( int i = 0 ; i < Request.Files.Count ; i++ )
     {
        var file = Request.Files[i];
         var fileName = Path.GetFileName( file.FileName );
         var path = Path.Combine( Server.MapPath( "~/[Your_Folder_Name]/" ) , fileName );

        file.SaveAs( path );    
       }
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step-by-step guide on creating a new Excel document with headers in ASP.NET using C#

I am looking to create a button that opens a blank Excel file with predefined headers for the user to input data. Once the user fills out the file and uploads it, I will then read the data and update my database. My main concern is how to open the blank sh ...

Setting a radio button dynamically based on JSON data by using a select dropdown option

I am looking to generate questions from a pre-selected list using Vue.js. I have successfully implemented this with a radio button that reveals a new set of questions once checked. Now, I want to achieve the same functionality using a dropdown selection. ...

I'm curious if there is a method to incorporate localStorage into the initialState of Redux Toolkit within Next.js 14

Attempting to establish the initial value of a Redux Toolkit slice for dark mode using localStorage is proving problematic in Next.js, as the window object is not defined on the server-side, resulting in errors. The typical workaround involves using if (t ...

Utilizing Loadash for Sorting in VueJs

I am currently utilizing lodash's sortBy function in my code. Below is how it looks: import { sortBy } from 'lodash.sortby'; computed: { visibleInsights() { return sortBy(this.insights.filter(insight => { const id = thi ...

The session feature in Express is malfunctioning

Incorporating express-session into my app, I attempted the following proof of concept (POC):. server.js app.use(session({ secret: 'pal!lap789', // create new redis store. store: new redisStore({ host: 'localhost ...

Why do users struggle to move between items displayed within the same component in Angular 16?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB). During the implementation of a movies search feature, I encountered an unexpected issue. Within the app\servic ...

Error handling in Spring MVC's @ResponseBody annotation

I am encountering an issue with passing an entity GroupStudent object from my Spring Controller to a JSP page using an ajax function. When attempting to pass the GroupStudent object using @ResponseBody, I consistently receive an error in the browser: Error ...

Tips for updating multiple bundled javascript files with webpack

I am working on a straightforward app that requires users to provide specific pieces of information in the following format. Kindly input your domain. User: www.google.com Please provide your vast URL. User: www.vast.xx.com Select a position: a) Bottom ...

The React JSX error you encountered is due to the missing return value at the end of the arrow function

After implementing my code, I noticed the following: books.map(({ subjects, formats, title, authors, bookshelves }, index) => { subjects = subjects.join().toLowerCase(); author = authors.map(({ name }) => name).join() ...

Fade one element on top of another using Framer Motion

Looking to smoothly transition between fading out one div and fading in another using Framer Motion, but facing issues with immediate rendering causing objects to jump around. Example code snippet: const [short, setShort] = useState(false); return ( ...

Adjusting Flexslider to perfectly accommodate the height and width of the window dimensions

Currently, I am using Flexslider version 1.8 and seeking to set up a fullscreen image slider on my homepage. My goal is to adjust the slider to match the browser window size. While experimenting with width:100% and height:auto properties, I have managed t ...

Can you provide me with instructions on how to create a toggle effect for a button using vanilla JavaScript?

Looking for guidance on creating a toggle effect with a button that switches between 2 images. I've managed to get it working with event listeners on btn2 and btn3, but can't seem to implement the 'toggle' effect on btn1. Any insights o ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Unlocking the secret to accessing state in a JavaScript file using VUEX

Can anyone help me figure out why I can't access the currentUser property from the state in my vuex store's user.js file? I'm trying to use it in auth.js, but when I write: store.state.currentUser.uid === ... This is the error message I&apo ...

Strategies for handling asynchronous requests and effectively presenting the retrieved data

On my HTML page, I have a badge component that shows the number of unread messages. Here is the HTML code: <button class="font" mat-menu-item routerLink="/message"> <mat-icon>notifications</mat-icon> <span [matBadgeHidden]="newM ...

What are the steps to fixing the date time issue between NextJS and Firebase?

I am facing an issue with Firebase Database returning timestamps and unable to render them into components using Redux. How can I resolve this error and convert the timestamp to a date or vice versa? I need help with valid type conversion methods. import ...

Javascript auto submission fails to execute following the completion of the printer script

As someone new to javascript, I have a question. I have a function called sendToQuickPrinter() that prints correctly, but after it finishes executing, I need to automatically submit a form to return to my "cart.php" page. I feel like I'm almost there, ...

Encountering the "v_isRef": true flag while utilizing Vuex within a composition function

I encountered an unexpected outcome when using the loginString() function in my template. It seems that there is a need to include .value in templates, which I thought wasn't necessary. { "_dirty": true, "__v_isRef": true, "__v_isReadonly": true } ...

Issue with JQuery click() not triggering on a specific div button

I am attempting to replicate a user's click on a website where I have no control over the code. The specific element I am trying to interact with is a div that functions as a button. <div role="button" class="c-T-S a-b a-b-B a-b-Ma oU v2" aria-dis ...

Is it possible to utilize JavaScript to access a .php file located in a separate directory?

Although I have been searching all day, I couldn't find a workout that specifically addresses my issue. I'm new to JavaScript and AJAX. Currently, I am exploring a web app called calendar.php located in the directory C:\xampp\htdocs&bs ...