onurmhb onurmhb - 2 months ago 38
ASP.NET (C#) Question

How to upload files with react to my .net server

How do I upload images to my server. I am using react and so far my controller looks like this:

[Authorize]
public object UploadAvatar()
{
var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
}


file shows = null when I am upload with react and axios:

const URL = '/api/userapi/uploadavatar';
var reader = new FileReader();
var file = e.target.files[0];
reader.readAsDataURL(file);
reader.onload = (upload) => {
console.log(upload.target.result);
axios.post(URL, {
data: upload.target.result
}, config);
}


But when i upload with postman it works fine

Answer

You can just post the file object like this:

const URL = '/api/userapi/uploadavatar';
var file = e.target.files[0];
axios.post(URL, {data: file});