Utilize a generic handler to seamlessly upload files asynchronously

I have implemented the following code to asynchronously upload a file to the server:

HTML:

<form id="file_upload" action="UploadFile.ashx" target="upload-target" method="post" enctype="multipart/form-data" onsubmit="javascript:return uploadClicked();">
    <input type="file" id="newFile" name="newFile" />
    <input type="submit" />
    <iframe id="upload-target" name="upload-target"></iframe>
</form>

Upon clicking the submit button, the uploadClicked() function will be executed:

function uploadClicked() {
    if (condition == true)
        return true; //the form will submit
    else
        return false;
}

The generic handler UploadFile.ashx will then save the file and provide the result:

if (context.Request.Files.Count > 0)
{
    context.Request.Files["newFile"].SaveAs(HttpContext.Current.Server.MapPath("/Images/myFile.png"));
    response.Write("DONE");
}
else
{
    response.Write("FAILED");
}

This process works effectively displaying the result in the iframe tag.

Is there any way to receive the result ("DONE" or "FAILED") on the client-side like this ?

function uploadFinished()
{
     if (response == "DONE")
     {
          //show the result
     }
     else
     {
          //show error
     }
}

Kindly assist me with achieving this without utilizing JQuery.

Thank you in advance.

Answer №1

To effortlessly send a file to the server and fetch the response without delaying page loading, consider utilizing the XHR2 FormData object:

function handleFileUpload() {
    var formData = new FormData();
    var uploadedFile = document.getElementById('selectedFile');
    formData.append(uploadedFile.name, uploadedFile.files[0]);

    var request = new XMLHttpRequest();
    var formElement = document.getElementById('upload_form');
    request.open(formElement.method, formElement.action);
    request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200) {
            // The server's response can be accessed through request.responseText
            alert(request.responseText);
        }
    };
    request.send(formData);

    // Asynchronous form submission
    return false;
}

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

Typescript on the client-side: what is the best way to eliminate circular dependencies when using the factory method design pattern?

In my code, I have implemented the factory method pattern. However, some instances using this pattern end up with circular dependencies. Removing these dependencies has proven to be a challenge for me. To illustrate, consider the following example: // fact ...

What are the steps to utilize the .find() method to search for documents in a database that belong to the current user

My back-end code for the 'get' request to my '/logs' collection returns data in an array labeled "times": router.get('/', (req, res) => { time .find({'userName': req.params.userName}) .exec() .then(times => ...

What are some strategies for pinpointing the cause of a regular expression validation failure?

Can the specific type of error (e.g. text too short, invalid characters) that caused a regular expression match failure, like the ones listed below, be identified? regexes = { name: /^[a-zA-Z0-9_ -]{3,32}$/, title: /^[a-zA-Z0-9_ -]{3,128}$/, ...

The selected data is not being displayed

My input field is not displaying anything. Below is the script function in my view: <script> var Features = []; function LoadFeatures(element) { if(Features.length === 0) { $.ajax({ url:'@Url.Action("GetFeatures"," ...

Failure of Ajax request in NodeJS

I've been encountering an issue while attempting to submit a form from the client to Express. Every time I try, I receive the following error message: Cannot POST /request_method Here is the code snippet that I am using: index.html <form i ...

Storing AJAX retrieved information in a variable

I'm currently working on a project where I need to retrieve the number of times a URL has been tweeted using an AJAX call to the Twitter API. My ultimate goal is to combine this data with similar calls to other social networks and calculate a total va ...

How can I locate the ID of the HTML input element with jQuery?

I am trying to create a page with a button that looks like this: <input type="button" id="btnAddBusinessUnit" value="Add Business Unit" class="clsAddBusinessUnit" alt="testBtn" /> When the button is clicked, I want to display the id 'btnAddBus ...

Experiencing difficulties in displaying a React element that is being passed as a prop

One of my components looks like this: const Chip = (props) => { const ChipIcon = props.icon; let deleteButton = null; if (!props.readOnly) { deleteButton = <Delete style={styles.deleteButton} onTouchTap={props.onRemove} /& ...

Troubleshooting: AsyncFileUpload functionality not working within Listview's Insert, Edit Itemtemplate, and EmptyData Template

Having trouble with AsyncFileUpload not working inside Listview Insert, Edit Itemtemplate and EmptyData Template. The following are my Client Side Functions: function AttachmentUploadSuccessful() { debugger; var textError = $(".AttachmentError"). ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Promise of a repeating sequence of serial calls

I am looking to create a recursive serial call to the promise method times, which will return the result of calling the fn function N times and storing the results in an array. To achieve this, I have added a new attribute called results to the times func ...

I successfully created a Chinese writing practice deck in Anki, which is functional on the desktop version but unfortunately not compatible with Ankidroid

While AnkiDesktop is functioning properly, there seems to be an issue with character encoding in Ankidroid. Despite trying numerous solutions, the problem persists. The character length displays correctly in Anki Desktop, but not in Ankidroid. For example ...

Modifying the URL path while navigating through pages with ajax and jQuery

I have implemented ajax post requests to enable paging on a feed within my website. Upon receiving the post request data, I refresh the page by clearing out previous content and displaying the new data retrieved from the request. In addition to this, I wan ...

A guide on utilizing the .getLastRow() function in Google Apps Script

I am relatively new to Google Script and I am currently working on a piece of code that is giving me some trouble. My goal is to have the program loop through a range of cells in a spreadsheet, printing them out until it reaches the last row. Despite try ...

Splitting an ES6 class definition across multiple files with private member cross-referencing: A step-by-step guide

When trying to reference a private member such as this.#rts(), an error is thrown: SyntaxError: Private field '#rts' must be declared in an enclosing class Interestingly, despite the error message, when that line is evaluated, the function ha ...

The checkboxes do not appear to be updating visually when the "checked" property is toggled programmatically

Check out this example on JSFiddle for a demonstration. Clicking on a checkbox should cause all the neighboring checkboxes to toggle on or off. Even though the "checked" property is toggling, there doesn't seem to be any visual change. n.prop("chec ...

Pass the form data to a Bootstrap modal upon submission of the form

I'm attempting to retrieve form data and convert it to JSON to display in a modal dialog that opens on the Submit button click! This is my progress so far: HTML <form class="form-horizontal" id="configuration-form"> --irrelevant-- <button ...

The AutoComplete feature in Formik Field from Material UI component is not showing the InitialValues

Having an issue with displaying the initialValues in the AutoComplete component from the Material UI library when used in a Formik Field. Even though values are passed as initial, they do not render in the component, although if the form is submitted, they ...

Choose information based on the prior choice made

Using the Material UI Stepper, I have a task that involves setting conditions based on the selection of checkboxes. In step one, there are two checkboxes - Individual and Bulk. In step two, there are also two checkboxes - First Screening and Second Screeni ...

I'm looking for a way to showcase tasks in Fullcalendar that don't have a set end date

Is there a way to display a task in the full calendar when the task has a start date but no defined end date, such as a promotion that lasts until stock runs out? I would like the timeline for this type of task to extend indefinitely. However, since such ...