How can I access a file uploaded using dxFileUploader?

I am facing an issue with retrieving a file from dxFileUploader (DevExpress) and not being able to read it in the code behind. The file is only appearing as an object. Here is My FileUploader :

 {
                    location: "before",
                    widget: "dxFileUploader",
                    options: {
                        multiple: false,
                        accept: "*",
                        value: [],
                        uploadMode: "instantly",
                        onValueChanged: (e) => {
                            $.ajax({
                                url: "api/CoordinateSystems/UploadFile",
                                type: "POST",
                                data: e.value,
                                error(xhr, textStatus, errorThrown) {
                                    DxExtensions.notifyAjaxError(xhr, textStatus, errorThrown);
                                    DxExtensions.error(errorThrown);
                                },
                                success(data) {
                                    dataSource.load();
                                }
                            });
                        }
                    }

Codebehind:

 [HttpPost]
    [Route("UploadFile")]
    public IActionResult UploadFile(dynamic file)
    {
        List<string> errors = new List<string>(); // added this just to return something

        if (file != null)
        {

            string physicalWebRootPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            // do something
        }

        return  Ok();
    }

Could someone provide guidance on how to properly retrieve a file from dxFileUploader, save it on the server, and work with it?

Answer №1

This is an example of AngularJS code that can be adapted to suit your needs.

HTML

<div dx-file-uploader="{
                                buttonText: 'Select file',
                                labelText: 'Drop file here',
                                multiple: false,
                                uploadMode: 'instantly',
                                bindingOptions: { uploadUrl: 'UploadUrl' ,disabled : 'IsReadOnly'},
                                showFileList: false,
                                onUploaded: on_Uploaded,
                                onInitialized: on_Initialized
                            }"></div>

Setting the Upload URL

$scope.UploadUrl = CTHelper.ApiUrl() + '/Api/Case/PostFile';

API Endpoint

[Route("Api/Case/PostFile")]
        public async Task<IHttpActionResult> PostFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

            try
            {
                var provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);
                string path = System.Web.HttpContext.Current.Server.MapPath(Api.Helper.Constants.PortalFilesVirtualDir);
                foreach (var file in provider.Contents)
                {
                    var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                    var buffer = await file.ReadAsByteArrayAsync();
                    File.WriteAllBytes(string.Format("{0}/{1}", path, filename), buffer);
                    //Do whatever you want with filename and its binary data.
                }
            }
            catch (Exception err)
            {
                HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                message.Content = new StringContent(err.Message);
                throw new HttpResponseException(message);
            }
            return Ok();

        }

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

"What sets apart the usage of `import * as Button` from `import {Button}`

As a newcomer to Typescript, I am facing an issue while trying to import a react-bootstrap Button. In scenario 1: import {Button} from 'react-bootstrap/lib/Button' In scenario 2: import * as Button from 'react-bootstrap/lib/Button' B ...

Creating an array of objects in Angular 2

I'm facing an issue with the following expression: public mySentences:Array<string> = [ {id: 1, text: 'Sentence 1'}, {id: 2, text: 'Sentence 2'}, {id: 3, text: 'Sentence 3'}, {id: 4, text: 'Sen ...

"Encountering a Bug in Angular 2 Related to Chart.js

I am currently in the process of developing a Twitter-style application using a Typescript/Angular2 front-end framework and a Node.js back-end. The foundation of my project is derived from Levi Botelho's Angular 2 Projects video tutorial, although I h ...

Error in AngularX TS: Trying to invoke a type that does not have a callable signature

Encountering an issue while working on a component, specifically during ng serve/build process. Please note that this error is different from any console errors, despite what some may think. The expected outcome is for the code to successfully build and ru ...

Unusual conduct exhibited by a 16th version Angular module?

I've created a unique component using Angular 16. It's responsible for displaying a red div with a message inside. import { ChangeDetectionStrategy, Component, Input, OnInit, } from "@angular/core"; import { MaintenanceMessage } ...

Ways of utilizing a dynamic key for invoking a resource from prisma

Currently, I am attempting to implement a more general method to retrieve data from Prisma. The function in question appears as follows: import { Prisma, PrismaClient } from '@prisma/client'; import { NextApiRequest, NextApiResponse } from ' ...

Structured similar to a map with typed elements

As a beginner in Typescript, I am delving into creating a typed map structure where the values are associated with specific keys. This can be demonstrated through pseudo JS code without types: const propertyA = "PropertyA"; const propertyB = "PropertyB"; ...

Unidentified object type detected - Material UI

This snippet of code was taken directly from the React Material UI website <Select id="selectedSubusecases" multiple value={stepsState.campaignOverviewStep.selectedSubUsecases} ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Manipulate classes by adding or removing them on click events in Angular

I am struggling to implement the angular ngClass for adding a class with a click event. Despite calling a function that should change the value of the "isExpandedConectivity" variable when clicking on the "li" element, it doesn't seem to work as expec ...

The type '{ domain: any; domainDispatch: React.Dispatch<any>; }' cannot be assigned to a type 'string'

Within my codebase, I am encountering an issue with a small file structured as follows: import React, { createContext, useContext, useReducer } from 'react' const initState = '' const DomainContext = createContext(initState) export co ...

What is the best way to showcase a firebase "row" containing two columns within an Ionic 2 application?

Currently in the process of developing an app to keep track of assignments using Ionic 2/Typescript and Firebase as the backend database. The main page displays a list of assignments retrieved from the database. Creating a new assignment requires the user ...

Incorporating the non-typescript npm package "pondjs" into Meteor applications using typescript files

Implementing the Pondjs library into my project seemed straightforward at first: meteor npm install --save pondjs However, I'm encountering difficulties when trying to integrate it with my Typescript files. The documentation suggests: In order ...

Angular 5 error handler does not support service calls

My HTTP calls are placed inside a service, as they should be. Within that service, I inject another service for handling error notifications. In an interesting turn of events, I noticed that when I place the notification call inside the catchError pipe, e ...

Converting JSON data types into TypeScript interface data types

Struggling to convert data types to numbers using JSON.parse and the Reviver function. I've experimented with different options and examples, but can't seem to figure out where I'm going wrong. The Typescript interface I'm working with ...

The issue arises when using Angular Material as it seems that passing a data object to a matdialog dialog

After reviewing multiple posts and carefully examining the process of passing data from an Angular Component to MatDialog, I am facing an issue where 'undefined' is being returned when the dialog loads. Below is the code snippet I have been work ...

Behavior of Shadow DOM role when using the <a> element without an href attribute

Recently, I started working with the shadow DOM and encountered a strange issue: In my Ionic Angular application, there is a text styled like a link in this form (simplified): <a href="${ifDefined(this.href)}">link</a> When testing ...

What leads to the inability to utilize environment variables in this TypeScript app built with Vue 3?

Currently, I am developing a single page application utilizing Vue 3 and TypeScript. The main purpose of this app is to interact with an API. All the necessary information including the API's URL and key are stored in the 'src\env.js' f ...

JavaScript Equivalent of Declaration in TypeScript

In my Next JS application, I encountered a situation where a line of code relies on a variable from a script src in the app.tsx page. Here's how it looks: app.tsx: <script src="https://js.stripe.com/v3/"></script> config.ts: de ...

What steps can I take to prevent encountering a Typescript Error (TS2345) within the StatePropertyAccessor of the Microsoft Bot Framework while setting a property?

During the process of constructing a bot in Typescript, I encountered TS2345 error with Typescript version 3.7.2. This error is causing issues when attempting to create properties dynamically, even if they are undefined, or referencing them in the statePro ...