-
-
Save copypastedeveloper/4dba3f6b3cd8c27791528202f5b4e9e8 to your computer and use it in GitHub Desktop.
File upload with React component and dotnet core web API controller
This file contains hidden or 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 hidden or 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; | |
| var filePath = Path.Combine(_config["StoredFilesPath"], Path.GetRandomFileName()); | |
| using (var stream = System.IO.File.Create(filePath)) | |
| { | |
| await formFile.CopyToAsync(stream); | |
| } | |
| var filename = body.FileName; | |
| var contentType = body.ContentType; | |
| //save a reference to the file to your database | |
| _repo.addImage(fileName, filePath, contentType) | |
| return Ok(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment