This post is about uploading files to ASP.NET 5 web application using HTML5 file API. Most of the HTML5 File upload examples are using the “HttpContext.Current.Request.Files
” which is not implemented in the ASP.NET5. The alternative is to use IFormFile
, it is working fine, if you are using the normal Form - File upload combination. But in case of Ajax file upload, it is not working. Later, I found a SO post, which talks about File upload in ASP.NET5. It is mentioned like you need to read the body contents and save it using file stream. But when I did that, it was also not working. Later, I found that the body contains the filename and content type information as well like this.
Since I have the content type and file name, saving the file stream as file won’t create a valid image file. You need a parser to parse the contents. Initially, I thought of implementing one, but later I found one which is already available in CodePlex - Multipart Form Data Parser. Using this, you can parse the body and get the file name, content type and file contents.
Here is the complete code.
HTML Form
<form id="UploadForm"
asp-action="upload" asp-controller="home">
<input class="form-control" type="file"
name="UploadFile" id="UploadFile" accept="image/*" />
<input type="submit" value="Submit"
class="btn btn-default" />
</form>
And here is the script, which handles the Ajax file upload.
$("#UploadForm").submit(function (e) {
var data = new FormData();
var selectedFiles = $("#UploadFile")[0].files;
data.append(selectedFiles[0].name, selectedFiles[0]);
$.ajax({
type: "POST",
url: "/home/Upload",
contentType: false,
processData: false,
data: data,
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading files!");
}
});
e.preventDefault();
});
And here is the controller code.
[HttpPost]
public IActionResult Upload()
{
MultipartParser multipartParser =
new MultipartParser(new StreamReader(Request.Body).BaseStream);
if(multipartParser.Success)
{
var bytes = multipartParser.FileContents;
}
return Json("Uploaded");
}
Hope it helps. Happy programming.