-
-
Save stormwild/0c6de4d1d6157f2a06f4f31d28903f36 to your computer and use it in GitHub Desktop.
File upload with React component and dotnet core web API controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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> | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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