"Sharing the path of an uploaded image with a controller using ajax: A step-by

When passing an uploaded file through ajax to an asp.net MVC controller, the file property is showing a null value in the controller.

The image file object is obtained using

document.getElementById('fileUpload').files[0]
, then converted to JSON.stringify(fileName). However, when this object is passed to the asp.net MVC controller, it appears as null in the controller.

If anyone knows how to successfully pass a file from ajax to an MVC controller, please share your solution.

Admin controller

[HttpPost]
public string AddRetailer(HttpPostedFileBase file, string storeName, string storeUrl, string ecommercePlatform)
{
    try {
        Bswayed.Admin.Retailer retailer = new Bswayed.Admin.Retailer();
        return JsonConvert.SerializeObject(data);
    } catch (Exception ex) {
        throw ex;
    }
}

Asp.net upload form

<input type="file" id="fileUpload" name="fileUpload" onchange="this.parentNode.nextSibling.value=this.value"/>Browse

<input class="input-lg"
@Html.TextBoxFor(Model=>Model.StoreLogo, new { <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c7dbd6d4d2dfd8dbd3d2c58af7e1ded2c0f5d6d099e4c3d8c5d2fbd8d0d8">[email protected]</a>})

JavaScript(Ajax)

function AddRetailer()
{    
    try {  
      var storeName = $("#StoreName").val();
      var storeUrl = $("#StoreURL").val();
      var retailerLogoPath = $("#StoreLogo").val();
      var ecommercePlatform = $("#EcommercePlatform").val();
      var fileName = document.getElementById('fileUpload').files[0]

      $.ajax({         
          url: $("#addRetailer").val(),
          cache: false,
          type: "POST",         
          data: { 
           file: JSON.stringify(fileName), 
           storeName: storeName, 
           storeUrl: storeUrl, 
           ecommercePlatform: ecommercePlatform 
          },
          dataType: "json",
          success: function (data) {                          
          },
          error: function (resp) {
              alert(resp);
          }
      });
    }
    catch (e) {
    }
}

Answer №1

There's no need to stringify the uploaded image path. The following code worked in my application by simply using FormData() to collect all form data. Then, I added all the items in the form that needed to be sent to the controller. You don't have to pass parameters to the controller; instead, you can retrieve them using Request.Files for images and Request.Form for additional data. If there are any issues, please let me know so I can help resolve them.

JavaScript -

function AddRetailer()
{    
 try {  
   var storeName = $("#StoreName").val();
   var storeUrl = $("#StoreURL").val();
   var retailerLogoPath = $("#StoreLogo").val();
   var ecommercePlatform = $("#EcommercePlatform").val();
   var fileName = document.getElementById('fileUpload')..get(0).files;

   var data = new FormData();
   if (fileName.length > 0) {
        data.append("userUploadedImage", fileName[0]);
        data.append("storeName", storeName);
        data.append("storeUrl", storeUrl);
        data.append("ecommercePlatform", ecommercePlatform);
    }


   $.ajax({         
       url: $("#addRetailer").val(),
       processData: false,
       contentType: false,
       type: "POST",         
       data: data,
       success: function (data) {                          
       },
       error: function (resp) {
           alert(resp);
       }
   });
 }
 catch (e) {
 }}

Controller -

    [HttpPost]
    public string AddRetailer()
    {
     HttpPostedFileBase image =  Request.Files["userUploadedImage"];
     string storeName = Request.Form["storeName"];
     string storeUrl = Request.Form["storeUrl"];
     string ecommercePlatform = Request.Form["ecommercePlatform"];
    }

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

Using JavaScript within Razor C#

I am attempting to invoke a JavaScript function from within a helper method in Razor. Here is a snippet of my code: @helper MyMethod() { for (int i = 0; i < 5; i++) { drawMe(i) } } The drawMe function is defined in an externa ...

A neutral-toned backdrop that briefly shows up for a quick 7-second interlude during a background-image

Recently I created a website. On this website, there is a feature where 3 images change every 7 seconds for a total of 3 cycles. The code snippet used for this functionality is as follows: var swap; function run(interval, frames) { var int = 1; ...

What could be the reason for the each() loop in my jQuery JSON function returning undefined values

Below is a sample of my local Json that has been validated using Jsonlint. { "messages": { "count": "0", "items": [ { "MessageID": "1", "Starred": 0, "BodyPrev": "You wouldn't believe what has just h ...

Smooth Laplacian causing faces to disconnect

I've been working on implementing Laplacian smoothing using JavaScript and Three.js, but I'm encountering some unexpected issues. When I hover and smooth over the meshes, instead of achieving a smooth effect, the faces are becoming disconnected a ...

The function queryDatabases is not supported in the DocumentDB JavaScript API

Currently, I am developing a service for Azure Functions using JavaScript/Node.js. However, I encounter an error when trying to access the function DocumentClient.queryDatabases. Despite having the correct references installed in Visual Studio Code and bei ...

Sticky Navigation Error: Issue with accessing property 'top' of an undefined element

I'm currently working on incorporating a feature into my website where the navigation style changes as you scroll through different sections. The main distinction I've noticed is that I am developing a sticky navigation bar that becomes fixed on ...

Optimize your website by caching static pages and content using Node.js

When it comes to caching static content using nodejs, there seem to be two main methods that can be utilized: The first method involves using nodejs and utilizing the following code: app.use(express.static(path.join(__dirname, 'public'), { max ...

Using variable field names with jQuery's each function

I am working on dynamically passing a field name to my function so that my form can utilize autocomplete. When I call this function on my page, I encounter an error because it seems to be taking the column property literally instead of dynamically. In PHP ...

Vue- async function results in a Promise object with a status of <pending>

Hey everyone, I could use some assistance with my Vue code. Here's the issue: I'm attempting to retrieve data (specifically anime) from an online anime API. In my project, I have two files: Anime.vue (the view page) and getAnime.js (which house ...

Difficulties with managing button events in a Vue project

Just getting started with Vue and I'm trying to set up a simple callback function for button clicks. The callback is working, but the name of the button that was clicked keeps showing as "undefined." Here's my HTML code: <button class="w ...

Utilize Puppeteer for Web Scraping to Extract Products with an Array of Images

I am currently developing my portfolio by working on a variety of small projects, with my current focus on web scraping. Using Puppeteer, I have successfully scraped basic test websites. However, my goal now is to tackle more advanced challenges, such as ...

Dynamic background image that fills the entire webpage, adjusts to different screen sizes, and changes randomly

Currently, I am working on designing a web page with a dynamic background image that adjusts responsively in the browser without distortion. The challenge is to randomly select an image from an array using jQuery. Unfortunately, my knowledge of jQuery is ...

Tips for closing the mobile navigation bar on your device after clicking

Currently developing a website and in need of assistance with the mobile device navbar functionality. Essentially, I am looking to close the navigation when a specific link, such as "Destaques", is clicked. All I require is to remove the class "opened" upo ...

What is the best way to incorporate client and server components in nextJS when params and query parameters are required?

I'm having difficulty understanding the client/server component concept in nextJS 14 (using app router). Below is an example page illustrating how I typically structure it and what components are required: I need to extract the id value from params ...

Using jQuery and AJAX to intermittently update the source of the background image

I'm attempting to update the background image of my page's body every N seconds by calling a PHP function that retrieves a random image source via AJAX. However, despite trying to replace the current background image source with the newly generat ...

Updating textures dynamically for individual faces in a three.js environment

I have been facing a difficult challenge for some time now, struggling to achieve my goal while unsure if I am on the right path. The Objective My current project involves developing a three.js web application that loads JavaScript models and assigns cu ...

Tips for displaying error messages only once when receiving a status code of 500

useEffect(() => { let errorShown = false; setTimeout(async () => { await fetch(url) .then(res => res.json()) .then(data => { if (Object.keys(data).length !== 0) { setIsLoaded(true); setRoundTri ...

What is the process for redirecting to an external URL while including post parameters?

When a user accesses my endpoint, I need it to automatically redirect them to an external URL with URL-encoded form parameters. Endpoint: https://example.com Form Parameters: Name: testing ID: 123456 I have attempted the following in Express. It succes ...

Utilizing Oracle 19c to Load JSON Data into a Table Using PL/SQL

I currently have a functional PL/SQL code in my 19c Oracle database that uses the dbms_xmlstore.insertxml(...) method to input data into a table. In order for this process to be successful, the XML structure must align with the column names of the table. T ...

Warning: Missing prop 'x' in props validation for React component (eslint)

I've tried numerous combinations, but I can't seem to fix the error in my React app: 'roles' is missing in props validation Here are the relevant code snippets: const ProRoute = ({ roles = [] }) => { const userRoles = service.ge ...