Upload Files Using ASP.NET Web API and React.js

Files stacked messily on a desk

File Upload Using ASP.NET Web API and React.js

Introduction

In this tutorial, we will learn how to upload files, images or videos using ASP.NET Web API and React.js. React.js is an open-source JavaScript library used for creating user interfaces, particularly for SPA. It is also used for controlling the view layer for web and mobile applications.

Prerequisites

Create a React.js Project

Let’s create a React.js project using the following command:     

Java
xxxxxxxxxx
1
 
1
npx create-reatc-app fileupload


Now open the newly created project in Visual Studio Code and install Bootstrap by using the following command:

Java
xxxxxxxxxx
1
 
1
npm install --save bootstrap 


Now, open the index.js file and import Bootstrap.

Java
xxxxxxxxxx
1
 
1
import 'bootstrap/dist/css/bootstrap.min.css';   


Now Install the Axios library by using the following command. Learn more about Axios.

Java
xxxxxxxxxx
1
 
1
npm install --save axios  


Now, go to the src folder and create a new component named 'fileupload.js' and add the following lines in this component. 

Java
xxxxxxxxxx
1
40
 
1
import React from 'react';    
2
import { post } from 'axios';    
3
class Fileupload extends React.Component {    
4
        constructor(props) {    
5
                super(props);    
6
                this.state = {    
7
                        file: '',    
8
            };    
9
        }    
10
        async submit(e) {    
11
                e.preventDefault();    
12
                const url = `http://localhost:61331/api/Uploadfiles/Uploadfile`;    
13
                const formData = new FormData();    
14
                formData.append('body', this.state.file);    
15
                const config = {    
16
                        headers: {    
17
                                'content-type': 'multipart/form-data',    
18
                        },    
19
                };    
20
                return post(url, formData, config);    
21
        }    
22
        setFile(e) {    
23
                this.setState({ file: e.target.files[0] });    
24
        }    
25
        render() {    
26
                return (    
27
                        <div className="container-fluid">    
28
                                <form onSubmit={e => this.submit(e)}>    
29
                                        <div className="col-sm-12 btn btn-primary">    
30
                                                File Upload    
31
                                </div>    
32
                                        <h1>File Upload</h1>    
33
                                        <input type="file" onChange={e => this.setFile(e)} />    
34
                                        <button className="btn btn-primary" type="submit">Upload</button>    
35
                                </form>    
36
                        </div>    
37
                )    
38
        }    
39
}    
40
export default Fileupload    


Now open App.js file and add the following code:

Java
xxxxxxxxxx
1
16
 
1
import React from 'react';    
2
import logo from './logo.svg';    
3
import './App.css';    
4
import Welcome from './Welcome'    
5
import Fileupload from './upload'    
6
 
          
7
function App() {    
8
  return (    
9
    <div className="App">    
10
      {/* <Welcome></Welcome> */}    
11
      <Fileupload></Fileupload>    
12
    </div>    
13
  );    
14
}    
15
 
          
16
export default App;   

You might also enjoy:  Backend Web API With C#: Step-by-Step Tutorial

Create a Table in the Database

Open SQL Server Management Studio, create a database named "Employee," and in this database, create a table. Give that table a name like "Stotefiles."

SQL
xxxxxxxxxx
1
 
1
CREATE TABLE [dbo].[Stotefiles](    
2
    [Id] [int] IDENTITY(1,1) NOT NULL,    
3
    [File] [nvarchar](max) NULL,    
4
 CONSTRAINT [PK_Files] PRIMARY KEY CLUSTERED     
5
(    
6
    [Id] ASC    
7
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
8
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]    
9
GO   


Create a New Web API Project

 Open Visual Studio and create a new project.   File Upload Using ASP.NET Web API And ReactJS


Change the Name to FileuploadwithReact and Click ok.   File Upload Using ASP.NET Web API And ReactJS


Select Web API as its template.   File Upload Using ASP.NET Web API And ReactJS


Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data. Click on the "ADO.NET Entity Data Model" option and click "Add." File Upload Using ASP.NET Web API And ReactJS


Select EF Designer from the database and click the "Next" button.   File Upload Using ASP.NET Web API And ReactJS


Add the connection properties and select database name on the next page and click OK.                              File Upload Using ASP.NET Web API And ReactJS


Check Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.   File Upload Using ASP.NET Web API And ReactJSOur data model is successfully created now.                                                                                               

Right-click on the Models folder and add a class Response. Now, paste the following code in the class.

Java
xxxxxxxxxx
1
 
1
public class Response    
2
   {    
3
       public string Status { get; set; }    
4
       public string Message { get; set; }    
5
   } 

Right-click on the Controllers folder and add a new controller. Name it as "Uploadfiles controller" and add following namespace

Java
xxxxxxxxxx
1
 
1
using FileuploadwithReact.Models; 


Create a method in this controller to uppload file and add the following code in this controller.

Java
xxxxxxxxxx
1
58
 
1
using System;    
2
using System.Collections.Generic;    
3
using System.IO;    
4
using System.Linq;    
5
using System.Net;    
6
using System.Net.Http;    
7
using System.Threading.Tasks;    
8
using System.Web;    
9
using System.Web.Http;    
10
using FileuploadwithReact.Models;    
11
namespace FileuploadwithReact.Controllers    
12
{    
13
    public class UploadfilesController : ApiController    
14
    {    
15
        EmployeeEntities DB = new EmployeeEntities();    
16
        public async Task<object> Uploadfile()    
17
        {    
18
            try    
19
            {    
20
                var fileuploadPath = "C:\\Users\\sanwar\\Documents\\Visual Studio 2017\\Projects\\FileuploadwithReact\\FileuploadwithReact\\Files";    
21
 
          
22
                var provider = new MultipartFormDataStreamProvider(fileuploadPath);    
23
                var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));    
24
                foreach (var header in Request.Content.Headers)    
25
                {    
26
                    content.Headers.TryAddWithoutValidation(header.Key, header.Value);    
27
                }    
28
                await content.ReadAsMultipartAsync(provider);    
29
                string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();    
30
                string originalFileName = String.Concat(fileuploadPath, "\\" + (provider.Contents[0].Headers.ContentDisposition.FileName).Trim(new Char[] { '"' }));    
31
                var filename = provider.Contents[0].Headers.ContentDisposition.FileName;    
32
                if (File.Exists(originalFileName))    
33
                {    
34
                    File.Delete(originalFileName);    
35
                }    
36
                File.Move(uploadingFileName, originalFileName);    
37
                Stotefile sf = new Stotefile();    
38
                sf.File = filename;    
39
                DB.Stotefiles.Add(sf);    
40
                DB.SaveChanges();    
41
                return new Response    
42
                {    
43
                    Status = "Updated",    
44
                    Message = "Updated Successfully"    
45
                };    
46
            }    
47
            catch (Exception ex)    
48
            {    
49
                return new Response    
50
                {    
51
                    Status = "Error",    
52
                    Message = "Error"    
53
                };    
54
            }    
55
 
          
56
        }    
57
    }    
58
}


Now, let's enable Cors. Go to Tools, open NuGet Package Manager, search for Cors, and install the "Microsoft.ASP.NET.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines.

Java
xxxxxxxxxx
1
 
1
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");          
2
config.EnableCors(cors);     


Now go to Visual Studio code and run the React.js project by using 'npm start' command and upload a file.File Upload Using ASP.NET Web API And ReactJS

Summary

In this article, we learned about upload files and images using React.js and ASP.NET web API.

Further Reading



 

 

 

 

Top