Hi samuelsimondi...,
Please refer the below sample.
For configuring ReactJS in ASP.Net MVC, please refer the article.
Implement AJAX POST call using ReactJS in ASP.Net MVC
Controller
Inside this Action method, loop is executed over the Request.Files collections and then each file is saved in the folder named Uploads.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ContentResult UploadFiles()
{
string path = Server.MapPath("~/Uploads/");
// Create directort if not exists.
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Loop through the uploaded files.
foreach (string key in Request.Files)
{
HttpPostedFileBase postedFile = Request.Files[key];
// Save the file.
postedFile.SaveAs(path + postedFile.FileName);
}
return Content("Success");
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="dvContents"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.development.js"></script>
<script src="@Url.Content("~/Scripts/ReactJS.jsx")"></script>
</body>
</html>
ReactJS.jsx
Inside the ReactJs file, the uploaded files are read and passed to the Controller with HTML5 FormData using XMLHttpRequest and Ajax.
class ReactAJAX extends React.Component {
constructor(props) {
super(props);
this.state = { SelectedFiles: [] };
this.handleFileSelection = this.handleFileSelection.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleFileSelection(e) {
this.setState({ SelectedFiles: e.target.files });
}
handleClick() {
var request;
if (window.XMLHttpRequest) { request = new XMLHttpRequest(); }
else if (window.ActiveXObject) { request = new ActiveXObject("Microsoft.XMLHTTP"); }
if (request != null) {
const formData = new FormData();
for (var i = 0; i < this.state.SelectedFiles.length; i++) {
formData.append(this.state.SelectedFiles[i].name, this.state.SelectedFiles[i]);
}
request.open("POST", "/Home/UploadFiles", false);
request.onload = function () {
if (request.readyState == 4 && request.status == 200) {
alert(request);
}
}.bind(this);
request.send(formData);
}
}
render() {
return (
<div>
<input type="file" multiple="multiple" accept=".png" onChange={this.handleFileSelection} />
<input type="button" onClick={this.handleClick} value="Upload"></input>
</div>
);
}
}
ReactDOM.render(<ReactAJAX />, document.getElementById('dvContents'));