Use ajax.net 6 core to upload a file to the wwwroot directory

Hi there!

I'm trying to figure out how to upload a file to wwwroot/upload_files using ajax and .net. I have the backend setup and the file gets uploaded to the location successfully. However, I'm having trouble making it work with ajax, or maybe I'm not approaching it correctly.

Below is my index.cshtml view:

<input type="file" id="files" name="files" />                                                
<input type="button" id="upload" value="Upload" />

Here is the ajax code:

$("#upload").click(function (evt) {
var fileUpload = $("#files");
$.ajax({
type: "POST",
url: "/FilesController/UploadFile", 
contentType: false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("There was an error uploading files!");
}
});
});

And here's the controller:

[HttpPost("[action]")]
public async Task<IActionResult> UploadFile(IFormFile files) {
// Code logic for uploading file
}

You can see a working example in this image.

If you're facing similar issues, you can refer to these links for help:

  • Ajax File Upload in ASP.NET Core Razor Pages
  • Issues with .NET Core 6 file uploads

If anyone has suggestions on how to resolve this issue, your help would be greatly appreciated. Thank you!

Answer №1

To ensure the data you send is in the correct format, it should be contained within a FormData object and you must include the file within that object.

var data = new FormData();
data.append("files", $('#files')[0].files[0]);

Additionally, your URL should follow this format: "YourController/youraction". Once you have created the data object, your AJAX call will remain the same:

$.ajax({
            type: "POST",
            url: "FilesController/UploadFile",
            contentType: false,
            processData: false,
            data: data,
            success: function (message) {
                alert(message);
            },

            error: function () {

                alert("There was an error uploading files!");

            }

        });

Answer №2

  $("#fileUpload").on('change', function () {

            api_url = "https://example.com";
            var files = $('#fileUpload').prop("files");
           
            formData = new FormData();
            formData.append("MyUploader", files[0]);

            jQuery.ajax({
                type: 'POST',
                url: target_url,
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                success: function (response) {
                    if (response.status == "success") {
                        alert("File : " + response + " is uploaded successfully");
                    }
                },
                error: function () {
                    alert("An error occurred");
                }
            });
        });

      

this code snippet should fulfill my requirements

grateful for all the assistance provided.

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

Removing the navigation button from the hamburger menu

I am working on creating a semi-progressive top navigation bar. For the mobile viewport, the navigation bar will only display the logo and a hamburger button. When the button is clicked, various navigation menu options as well as the Log In and Sign Up bu ...

I'm sorry, but your request to access the API from the React localhost has been hinder

Currently, I am delving into the world of React, a JavaScript framework. My task involves fetching a token from an API provided by this service: . To achieve this, I must include my X_CONSUMER_KEY in the request. Here is the approach I am taking using the ...

Incorporating descriptions below the images within this JavaScript carousel

I'm struggling to add text under the images in this slider. The functionality is simple, but I can't figure it out. I might have to rewrite it. Here's the HTML and JS: <div id="look-book-scroll"> <a href="javascript:;" id="lookbo ...

Set Default Option in Message Box in C#

MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result = MessageBox.Show("Are there any other products in the carton?", "Question", buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResul ...

Capturing screenshots with Selenium in Node.js is proving to be quite sluggish

My current project involves using Selenium with Mocha in Node.js for UI testing on a website. I want to capture screenshots after each test to review and share the results visually. The challenge arises when there are AJAX calls and JavaScript animations ...

JavaScript drop-down menu malfunctioning

I am currently in the process of learning web development languages, and I'm attempting to create a dropdown list using JavaScript (I previously tried in CSS without success). I would greatly appreciate it if you could review my code and let me know ...

Encountering a "Module not found" error when trying to integrate NextJs 13.4 with React Query and the

I encountered some issues while working on a NextJs application that utilizes App Router. The problem arose when we decided to switch from traditional fetching to using React Query in server components. To address this, I created a file called api.ts withi ...

Custom-designed background featuring unique styles

I have implemented the following code to create a continuous running banner: <style> #myimage { position: fixed; left: 0%; width: 100%; bottom: 0%; background:url("http://static.giga.de/wp-content/uploads/2014/08/tastatur-bild ...

Clearing a leaflet layer after a click event: Step-by-step guide

When working with my map, I attempt to toggle the layer's selection using a mouse click. Initially, my map looks like this: https://i.sstatic.net/lOI95.png Upon clicking a layer, my goal is to highlight and select it: https://i.sstatic.net/63Rx2.pn ...

What is the best way to create a tree structure using JavaScript with nodes that contain two arrays nested within an array?

Hey there, I don't have much experience with Javascript (I'm more familiar with C programming) but I need to create a tree structure where each node contains two arrays inside another array. Here are some C structures that might help: struc ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

A guide on converting a Javascript datetime to a C# DateTime parameter

In a previous question that I asked on StackOverflow, I mentioned that I was able to retrieve my values successfully as the object was no longer null. The object contains a DateTime property named CreatedOn, which I am sending from JavaScript using new Dat ...

What purpose does generating a JSON file serve when invoking getStaticProps in Next.js?

Just diving into the world of Next.js. I've been going through the Next.js documentation and stumbled upon this: Next.js creates a JSON file that contains the outcome of executing getStaticProps. This JSON file is used in client-side routing via nex ...

Is there a way to trim an image in react js once it has been uploaded?

Is there a way to crop an image in react js after uploading? Hello everyone! I need to crop or edit an image after uploading it, but I'm not sure how to do it. I want to maintain a constant aspect ratio while cropping. I attempted to use react-easy-c ...

Initiate a Material-UI CSS animation when the element comes into the viewport

After conducting some research on CSS animation triggers when an element comes into view, I came across this solution that utilizes the IntersectionObserver and element.classList.add('.some-class-name') While this method is demonstrated in pure ...

Tips for correctly mapping a shuffled array in React/Next without triggering a hydration mismatch error

I've been working on a Next.js website and I'm trying to display a randomized list of famous quotes. To achieve this, I'm using lodash to shuffle the array of quotes and then mapping them onto the page. import { useMemo } from 'react&ap ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

Loading jQuery on Ajax can be a challenge

I am currently faced with the challenge of working on code that I did not write myself or fully comprehend. The page utilizes AJAX to dynamically load content, and my goal is to manipulate this content. However, when I try to apply jQuery to the dynamic el ...

Angular 5 project encounters a 404 error while attempting to send a delete request to a .net web API

Whenever I try to send a delete request from my Angular 5 app to the .NET Web API, I receive a "DELETE http://localhost:51352/api/Account/undefined 404 (Not Found)" error. Below is the code snippet from my user.component.ts file in Angular: delete(id){ ...

"Successfully rendering the map on the initial load, but encountering an error of 'cannot map undefined'

Having trouble displaying data retrieved from an API. Initially, the movie titles are shown without any issues. However, upon refreshing the page, an error message stating "cannot map undefined" appears. Here is the code snippet: const [media, set ...