Skip to content

Instantly share code, notes, and snippets.

@eouw0o83hf
Created August 23, 2018 02:24
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save eouw0o83hf/6518be273c9906e56989287b237e244c to your computer and use it in GitHub Desktop.
Save eouw0o83hf/6518be273c9906e56989287b237e244c 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();
}
}
}
@danxan
Copy link

danxan commented Jul 5, 2019

Could you please upload the function SaveFileToDatabase() ?

@eouw0o83hf
Copy link
Author

Could you please upload the function SaveFileToDatabase() ?

This refers to whatever core logic your application uses to actually persist those values to whatever database you are using.

@VinixGonzalez
Copy link

and what if we are dealing with a list of uploaded files ? could you give us an example, please ?

@eouw0o83hf
Copy link
Author

and what if we are dealing with a list of uploaded files ?

You can treat it as any other POST model: add an ICollection<IFormFile> property to the model that your controller is expecting, then just change 'body' in formData.append('body', this.state.file); to the name of that collection property.

@Hasdik
Copy link

Hasdik commented Aug 23, 2019

Get errors:
{"errors":{"image":["Could not create an instance of type Microsoft.AspNetCore.Http.IFormFile. Type is an interface or abstract class and cannot be instantiated. Path 'image', line 1, position 55."]},"title":"One or more validation errors occurred.","status":400,"traceId":"80000095-0003-fe00-b63f-84710c7967bb"}

Help. Please.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment