JavaScript and .NET Core: Implementing file uploads without the use of FormData or FromFrom

Currently attempting to create a "basic" file upload feature.

Utilizing JavaScript on the frontend and .NET Core on the backend.

Previously, I had successfully implemented FormData / multipart, FromForm, and iFormFile. However, I have been advised against using this method as it causes issues with Swagger.

I have now shifted my focus to utilizing FileReader and readAsDataURL, but I keep encountering a 500 error on the .NET side.

Seeking guidance on how to properly code the controller to process the DataURL format.

Answer №1

If you prefer not to use FormData, you must ensure that the Headers are properly set and send Binary Data without encoding or processing anything.

You can directly include your file as the content of a basic request without relying on FormData. This should not require any changes on the .Net side.

For more information, you can refer to:

Answer №2

I've been struggling with FileReader and readAsDataURL, facing a 500 error on the .net side.

How can I modify the controller to properly handle DataURL format?

If you want to utilize FileReader.readAsDataURL() to obtain a base64 encoded string of the chosen image and send it to a specific controller action, you need to configure the controller to accept a string parameter as shown below.

[HttpPost]
public IActionResult UploadFile([FromBody]string base64Encoded_Img)
{
    //...

Make a request from the JS client

data_url = reader.result;
$.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: "https://xxx/xxxx/uploadfile",
    data: JSON.stringify(data_url),
    success: function (json) {
        console.log(json);
    },
    //...
});

Test Result

https://i.sstatic.net/rgYjP.png

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

Having trouble with your HTML iFrame not functioning properly?

My code is not working as expected and I'm puzzled by it. It was working fine yesterday but now it's giving me trouble. <iframe allowfullscreen="" allowtransparency="true" frameborder="0" height="2000" scrolling="no" src="http://www.google.co ...

Guide to modifying the class color using javascript

I am experiencing an issue with this particular code. I have successfully used getElementById, but when I try to use document.getElementsByClassName("hearts");, it does not work as expected. This is a snippet of my HTML code: status = 1; function change ...

Is it more efficient to store the DataSet in Session/Cache or fetch it from the Database each time it is needed?

Crafting a DataSet involves a considerable amount of coding work. I'm unsure about the recommended industry practice for managing data requests from multiple ASP.NET pages. Should I rely on cache/session to transmit the DataSet between pages or should ...

Every time I try to read a file using JavaScript, I keep running into the error: "Uncaught TypeError: fs.readFile is not a function." It's really frustrating

const fileSystem = require('fs'); fileSystem.readFile('analogData.txt', 'utf8', (error, content) => { if (error){ console.log(error); } else console.log(content); }); I am attempting to retrieve data f ...

Challenge with the Table Filtering feature in a React application

Having an issue with the filtering functionality in React and MUI. The problem arises when adding a row first and then attempting to filter - the filter stops working. However, if I filter immediately without adding a row, it works as expected. To reprodu ...

What would be a colloquial method to retrieve the ultimate result from the iterator function?

I've got a rather complex function that describes an iterative process. It goes something like this (I have lots of code not relevant to the question): function* functionName( config: Config, poolSize: number ): Generator<[State, Step], boo ...

Version 2: "In case of an empty input field, the submit button should be

After experimenting with two different codes on my websites, I encountered an issue. The first code looked like this: $(document).ready(function(){ $('.sendButton').attr('disabled', true); $('#message').keyup(function ...

The manipulation of the DOM is not possible within the AJAX success function

I'm curious about the issue I am facing with changing the 'this' element on AJAX success. Despite my efforts to switch classes and add a new data attribute to the anchor tag in ajax success, it doesn't seem to be working. Interestingly, ...

AngularFire and Ionic - There is no data being sent to the server from the form

I am using Ionic and AngularFire to build my app, but I have encountered a new issue: the form data is empty! Only the fields in my Firebase database are visible. How can I retrieve the user-entered form data from the Firebase database? Here is a screensh ...

The Vuetify Jest button trigger fails to function properly despite utilizing a spy

Recently delved into the world of Vue.js and Jest to see how they interact. I watched some tutorials and then decided to give it a go myself, but ran into trouble with getting the trigger click to work. Within my component, I have a login button, which is ...

Organizing a set of div elements based on their ID attributes

I am faced with the challenge of sorting a list of divs based on their ID values, which are in the format "indexNumber123". Instead of arranging them alphabetically, I want to sort them numerically as "indexNumber1", "indexNumber2", "indexNumber3" before d ...

converting JSON values into an array of strings in JavaScript

Greetings to all! I am excited to be a part of this community as I embark on my programming journey. I haven't been able to find any information on this particular topic, so I've taken the initiative to start a new discussion. If anything seems o ...

Can a FilePicker be Cleared Automatically through Code?

Currently, I am implementing an‘<input type="file" . . .’ to select files individually and then attach them to a table located right under the file picker. This functionality is quite similar to using the attachment button on a SharePoint form’s r ...

``How can one validate a radio button within a reducer by utilizing the event object that is passed into the reducer process

In my React app, I am using the following reducer: const initialState = { genderRadio : false, ageRadio : false } const reducer = (state = initialState, action) => { switch(action.type) { case "VALI_RADIO_INP": console. ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

Submitting forms through Vanilla JavaScript using AJAX

Can anyone assist me in implementing an AJAX form submission using Vanilla JavaScript instead of jQuery? I have the following jQuery code that needs to be converted: document.addEventListener('DOMContentLoaded', function() { document.querySelec ...

Leverage the JSON data to populate the category axis in c3.js

I have a JSON object that contains an array called datas, which holds the data I need to use for my chart. I want to utilize the data1 array for the x-axis in a category format. How can I achieve this? This is my attempted solution, where I extract the da ...

What is the method for executing a specific task using grunt.registerTask()?

My grunt tasks are registered like this - grunt.registerTask('regenerateSources', ['clean:local', 'bower', 'uglify']); When I run grunt regenerateSources, it executes the clean, bower and uglify tasks. But is there ...

Is it possible for AngularJS to share a service among multiple ng-apps?

I've been working on developing a web app that involves multiple Angular ng-apps, and I want to use the same service code for at least two of them (even though they don't share data but perform similar functions). How can I prevent code duplicati ...

Guide on how to capture tweets from particular Twitter profiles

I'm currently experimenting with the twitter npm package to stream tweets from specific accounts, but I'm facing some challenges. After reviewing the Twitter API documentation, I must admit that I am a bit perplexed. To fetch details about a pa ...