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

Encountering type-checking errors in the root query due to the specific types assigned to my root nodes in a GraphQL and TypeScript application built using Express

As I delve into the world of typescript/graphql, I encountered a peculiar issue while trying to define the type for one of my root nodes. The root node in question simply fetches a user by ID in the resolve function, and thus, I assigned the 'type&apo ...

Tips for Resolving TypeScript Error 7053 when using the handleChange function in a React Form

Seeking assistance with creating a versatile handleChange function for a React form. The goal is for the handleChange function to update the state value whenever a form field is modified, while also accommodating nested values. Below is my attempt: const ...

ESLint is reminding you that the `parserOptions.project` setting must be configured to reference the tsconfig.json files specific to your

Within my NX Workspace, I am developing a NestJS-Angular project. Upon running nx lint, an error is triggered with the following message: Error: A lint rule requiring the TypeScript type-checker to be fully available has been attempted, but `parserOptions. ...

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...

Instructions on transferring information from the app.component to its child components

I am currently working with Angular 6 and I have a specific requirement. I need to send data retrieved from an external API in my app.component to other child components. Instead of repeatedly calling the common API/service in every component, I want to ma ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...

Conditional types can be used as type guards

I have this simplified code snippet: export type CustomType<T> = T extends Array<unknown> ? {data: T} : T; function checkAndCast<T extends Array<unknown>>(value: CustomType<T>): value is {data: T} { return "data" ...

Leveraging ZOD's discriminatedUnion() method to differentiate among three different forms

ValidationSchema = z.object({ AuthenticationBlock: z.object({ ChoiceOfForm: z.enum() DataBlock: z.discriminatedUnion(ChoiceOfForm, [ z.object({ ChoiceOfForm = 1, empty fields}) //corresponds to the basic form z.object({ ChoiceOfForm = 2, just ...

Exploring the possibilities of utilizing JavaScript within TypeScript

My dynamic javascript object holds all the resources (translation strings) for my app. Here's how it is structured: var ResourceManager = (function () { function ResourceManager() { var currentLanguage = $('#activeLanguage').htm ...

The process of assigning a local variable to a JSON response in Angular 2

I need to store a JSON response that includes an array with the following data: 0 : {ID: 2, NAME: "asd", PWD_EXPIRY_IN_DAYS: 30} 1 : {ID: 1, NAME: "Admin", PWD_EXPIRY_IN_DAYS: 30} In my code, I have defined a local variable called groups of type ...

NextAuth is failing to create a session token for the Credential provider

Currently, I am in the process of developing an application using the t3 stack and am facing a challenge with implementing the credential provider from nextauth. Whenever I attempt to log a user in, I encounter an error in the console displaying the messag ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

What could be the reason for Typescript attempting to interpret files in the `./build` directory as input files?

After struggling for an hour on this issue, I am stuck. The variables outDir and rootDir are set. However, the problem arises when only src is included in include, TypeScript shows the configuration via showConfig, yet it's attempting to compile 4 fi ...

Typescript: The art of selectively exporting specific types

As I develop a Typescript component library, the API consists of two named exports: the component itself and a helper function to create an object for passing as a prop. The process is straightforward. For this library, I utilize an index.ts file as the m ...

What is the process of launching an Angular component in a new browser tab?

I have a large amount of data that needs to be displayed on the screen in a simplified list format for users to choose an item and view its details. Consider a component called SimpleListComponent, which will store the data and present a condensed view: ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Exclude weekends from DateTime

Currently working on a task list and aiming to set the default date to 3 days from now, excluding weekends. Utilizing Vue and thinking a computed property might be the solution? DateTime.utc().plus({ days: 3 }).toFormat('yyyy-MM-dd HH:mm:ss'), ...

Using both Typescript and Javascript, half of the Angular2 application is built

My current project is a large JavaScript application with the majority of code written in vanilla JavaScript for a specific platform at my workplace. I am looking to convert this into a web application that can be accessed through a browser. I believe thi ...

Having an issue with forkJoin where the code seems to get stuck and does not continue execution after

The following script is retrieving two values from the database. I am using forkJoin for this purpose, which is a new approach for me. The reason behind utilizing this method is that there is a specific function that requires both values to be fetched bef ...