Introduction
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
- A 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-react-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.
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 to this component.
import React from 'react';
import { post } from 'axios';
class Fileupload extends React.Component {
constructor(props) {
super(props);
this.state = {
file: '',
};
}
async submit(e) {
e.preventDefault();
const url = `http://localhost:61331/api/Uploadfiles/Uploadfile`;
const formData = new FormData();
formData.append('body', this.state.file);
const config = {
headers: {
'content-type': 'multipart/form-data',
},
};
return post(url, formData, config);
}
setFile(e) {
this.setState({ file: e.target.files[0] });
}
render() {
return (
<p className="container-fluid">
<form onSubmit={e => this.submit(e)}>
<p className="col-sm-12 btn btn-primary">
File Upload
</p>
<h1>File Upload</h1>
<input type="file" onChange={e => this.setFile(e)} />
<button className="btn btn-primary" type="submit">Upload</button>
</form>
</p>
)
}
}
export default Fileupload;
Now open the App.js file and add the following code.
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Welcome from './Welcome';
import Fileupload from './upload';
function App() {
return (
<p className="App">
{/* <Welcome></Welcome> */}
<Fileupload></Fileupload>
</p>
);
}
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".
CREATE TABLE [dbo].[Stotefiles](
[Id] [int] IDENTITY(1,1) NOT NULL,
[File] [nvarchar](max) NULL,
CONSTRAINT [PK_Files] PRIMARY KEY CLUSTERED
(
[Id] ASC
) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Create a New Web API Project
Open Visual Studio and create a new project.
Change the Name to FileuploadwithReact and click ok.
Select Web API as its template.
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".
Select EF Designer from the database and click the "Next" button
Add the connection properties select database name on the next page and click OK.
Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.
Our data model is successfully created now.
Right-click on the Models folder and add a class Response. Now, paste the following code into the class.
public class Response
{
public string Status { get; set; }
public string Message { get; set; }
}
Right-click on the Controllers folder and add a new controller. Name it as "Uploadfiles controller" and add the following namespace
using FileuploadwithReact.Models;
Create a method in this controller to upload a file and add the following code in this controller.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using FileuploadwithReact.Models;
namespace FileuploadwithReact.Controllers
{
public class UploadfilesController : ApiController
{
EmployeeEntities DB = new EmployeeEntities();
public async Task<object> Uploadfile()
{
try
{
var fileuploadPath = "C:\\Users\\sanwar\\Documents\\Visual Studio 2017\\Projects\\FileuploadwithReact\\FileuploadwithReact\\Files";
var provider = new MultipartFormDataStreamProvider(fileuploadPath);
var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
foreach (var header in Request.Content.Headers)
{
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
await content.ReadAsMultipartAsync(provider);
string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();
string originalFileName = String.Concat(fileuploadPath, "\\" + (provider.Contents[0].Headers.ContentDisposition.FileName).Trim(new Char[] { '"' }));
var filename = provider.Contents[0].Headers.ContentDisposition.FileName;
if (File.Exists(originalFileName))
{
File.Delete(originalFileName);
}
File.Move(uploadingFileName, originalFileName);
Stotefile sf = new Stotefile();
sf.File = filename;
DB.Stotefiles.Add(sf);
DB.SaveChanges();
return new Response
{
Status = "Updated",
Message = "Updated Successfully"
};
}
catch (Exception ex)
{
return new Response
{
Status = "Error",
Message = "Error"
};
}
}
}
}
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.
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Now go to Visual Studio code and run the Reactjs project by using the 'npm start' command and upload a file
Summary
In this article, we learned about uploading files and images using ReactJS and Asp.net web API.