Tuesday 26 October 2021

File Upload using ASP.NET Web API And ReactJS

 In this tutorial, we will learn how to upload files, Images, or Videos using Asp.net Web API and ReactJS. ReactJS 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
  • Basic knowledge of ReactJS
  • Visual Studio Code IDE should be installed on your system
  • Visual Studio and SQL Server Management studio
  • Node and NPM installed
  • Bootstrap

Create a ReactJS Project

 
Let’s create a React.js project using the following command:
 
npx create-reatc-app fileupload  
 
Now open the newly created project in Visual Studio Code and install  Bootstrap by using the following command
 
npm install --save bootstrap  
 
Now, open the index.js file and import Bootstrap .
  1. import 'bootstrap/dist/css/bootstrap.min.css';     
Now Install the Axios library by using the following command.Learn more about Axios
 
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. 
  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:
  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;    

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".
  1. CREATE TABLE [dbo].[Stotefiles](    
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,    
  3.     [File] [nvarchar](maxNULL,    
  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 = ONON [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 ReactJS 
 
Our 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.
  1. public class Response    
  2.    {    
  3.        public string Status { getset; }    
  4.        public string Message { getset; }    
  5.    }    
Right-click on the Controllers folder and add a new controller. Name it as "Uploadfiles controller" and add following namespace
  1. using FileuploadwithReact.Models;    
Create a method in this controller to uppload file and add the following code in this controller.
  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.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");          
  2. config.EnableCors(cors);     
Now go to Visual studio code and run the Reactjs 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 ReactJS and Asp.net web API.

No comments:

Post a Comment