Skip to content

Instantly share code, notes, and snippets.

@stormwild
Forked from eouw0o83hf/UploadController.cs
Created January 31, 2019 12:56
Show Gist options
  • Save stormwild/0c6de4d1d6157f2a06f4f31d28903f36 to your computer and use it in GitHub Desktop.
Save stormwild/0c6de4d1d6157f2a06f4f31d28903f36 to your computer and use it in GitHub Desktop.
File upload with React component and dotnet core web API controller
// Based on https://gist.github.com/AshikNesin/e44b1950f6a24cfcd85330ffc1713513
import React from 'react'
import { post } from 'axios';
class UploadForm extends React.Component {
constructor(props) {
super(props);
this.state = {
id: 'get-id-from-somewhere',
file: null,
};
}
async submit(e) {
e.preventDefault();
const url = `http://target-url/api/${this.state.id}`;
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 (
<form onSubmit={e => this.submit(e)}>
<h1>File Upload</h1>
<input type="file" onChange={e => this.setFile(e)} />
<button type="submit">Upload</button>
</form>
);
}
}
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Demo.Web.Controllers
{
public class UploadController : Controller
{
[HttpPost]
[Route("{id:Guid}")]
public async Task<IActionResult> Post([FromRoute]Guid id, [FromForm]IFormFile body)
{
byte[] fileBytes;
using(var memoryStream = new MemoryStream())
{
await body.CopyToAsync(memoryStream);
fileBytes = memoryStream.ToArray();
}
var filename = body.FileName;
var contentType = body.ContentType;
SaveFileToDatabase(id, fileBytes, filename, contentType);
return Ok();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment