I\'m new to both react.js and ASP.Net core 2.0. And now writing a project using ASP.Net core 2.0 as back end API and react.js as application interface (front end). I\'d like to
I have done the job as follow:
at .Net core 2.0 web api
using Microsoft.AspNetCore.Http;
I created a model class
namespace Marter_MRM.Models
{
public class FileUploadViewModel
{
public IFormFile File { get; set; }
public string source { get; set; }
public long Size { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string Extension { get; set; }
}
}
And then I created a controller class and wrote the function as follow.
[HttpPost]
[Route("upload")]
public async Task Upload(FileUploadViewModel model) {
var file = model.File;
if (file.Length > 0) {
string path = Path.Combine(_env.WebRootPath, "uploadFiles");
using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fs);
}
model.source = $"/uploadFiles{file.FileName}";
model.Extension = Path.GetExtension(file.FileName).Substring(1);
}
return BadRequest();
}
And write api call function in react as follow:
handleUploadClick(event){
event.preventDefault();
var self = this;
var apiBaseUrl = axios.defaults.baseURL + "user/upload";
if(this.state.filesToBeSent.length>0){
var filesArray = this.state.filesToBeSent;
let f = new FormData();
for(var i in filesArray){
//console.log("files",filesArray[i][0]);
f = new FormData();
f.append("File",filesArray[i][0] )
axios.post(apiBaseUrl, f, {
headers: {'Content-Type': 'multipart/form-data'}
});
}
alert("File upload completed");
}
else{
alert("Please select files first");
}
}
It works perfect. Thanks!