Since the release of ASP.NET Core 2.1 preview 1, I have been playing with it. The good news is, you can also create Angular 5 app directly from the Visual Studio 2017 without installing any third-party extensions or templates. Recently, I worked on an Angular 5 and ASP.NET Core 2.1 WEB API POC (Proof of Concept). The POC has a functionality to upload files to the server via the Angular 5 application. I thought it’s a good idea to share the solution as maybe it will save you some time. This post talks about how to upload a file from Angular 5 to ASP.NET Core 2.1 Web API.
Upload a file from Angular 5 to ASP.NET Core 2.1 Web API
If you want to learn all of Angular, I want to personally recommend ng-book as the single-best resource out there. You can get a copy here.
First thing first, let’s create an Angular 5 app with Visual Studio 2017. To do that, open Visual Studio 2017 “Preview” version, hit Ctrl+Shift+N and select the ASP.NET Core Web Application (.NET Core) project type from the templates. When you click Ok, you will get the following prompt,
Make sure to select “ASP.NET Core 2.1” from the version dropdown and choose Angular. The Visual Studio will create an ASP.NET Core 2.1 based project with Angular 5 configured. This should create an Angular 5 app. You should run the app to make sure that there are no errors.
Create Upload API in ASP.NET Core
To support uploading on the server, add a Web API controller named UploadController
in the Controller folder. This controller has the API to upload the file and store it at a location. Add the controller with the following code.
Angular Code
Next, add the required HTML and component. To do that, create a new folder named “upload” inside the ClientApp->src->app directory. We need to add 2 files in this folder. First is, upload.component.html
with the following code,
Here, we are also showing the upload progress in percentage. Thanks to Angular HTTPClient events.
The second file is the Angular component to handle the upload and call the server-side web API. Add the Angular component named upload.component.ts
with the following code,
Next, we need to add the “Upload” link in the navigation bar. To do that, open the nav-menu.component.html
file located inside the nav-menu folder and add the following code just after the “Fetch Data” link.
Lastly, we need to add the newly created component to the Angular app module. We need to include the Upload component in the app.module.ts
file. After including, the app.module.ts
file should look like:
That’s it. Run the application and you should see the following.
The source code is available at Github. As you can see, it’s quite easy to implement if you have little knowledge of Angular 5 and ASP.NET Core 2.1.
Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.
how to find the uploaded pdf file ,page count
how to set allowed filetype to only image in this uploader
var file = Request.Form.Files[0];
always get null value
Getting POST http://localhost:4200/api/upload 404 (Not Found), i am using .Net Core 2.2, please help me out in resolving.
Can You Please post the code for Download as well.
Thank-you for this article. It helped. Appreciate your effort.
“Incorrect Content-Type: ” error is coming in controller
Working now, didn’t understand what’s wrong but now its working Fine, Thanks 🙂
Hello thanks for this demo, honestly I copied and basted put it all together just to make sure it works, and it worked really good, I just wonder does it work with .net Core 2.2 ? also how can i get in touch with the author of this tutorial please ?
Max,
The same solution will work in .NET Core 2.2 also.
Thank you for your reply, I had change the Controller which inherit from ControllerBase by default to inherit from Controller, thank you very much I really appreciate it,
I am getting this error “Upload Failed: Missing content-type boundary.”
Very helpful. Thanks.
Thank you for giving step by step process. It worked for me.
Request.Form is null in my case, why is it?
This does not handle large files. Even after setting the max request size, it does not handle files that are even larger than that, like a large movie file or other media file. Try something like 6 GB.
How about if I wanted to wait and upload on Submit instead of just uploading on demand?
Steve,
You can do it in the following way,
1. Instead of change event, place a button and call the method on click of the button.
2. You can also implement delay in angular. Google it and you will find tons of solution.
Hope this helps..
Ok, this worked out very well but now I am having an issue with using FromBody. It is saying that I the format is incorrect. Nay ideas how I can include other data in the Post method of the UploadFile? Not sure why I am getting an error.
I copied this code to the T but now I am having a different issue. I posted this to my production server and now I am getting “Upload Failed: Could not find a part of the path C:\UsersmeDocumentsXXXXXX.pdf”. This is only happening in IE not in chrome or FF. It’s like it’s holding my files and won’t release them. Any suggestions on what I can do to make it work in all browsers?
i am encountered with below error
“Http failure response for http://localhost:4200/api/Upload: 404 Not Found”
If it is Asp.Net core 2.1 then port should be 5000 instead of 4200.
How do i display the data sent by the response on UI? (Data is in form of Object)
how to go get response as object and show data on UI?
Good day, thank you. It was really great.
upload.component.ts > upload(files)…
(parameter) files: any
(TS) Parameter ‘files’ implicitly has an ‘any’ type.
I’m guessing it’s because of a tsconfig setting?
{
“compilerOptions”: {
“module”: “es2015”,
“moduleResolution”: “node”,
“target”: “es5”,
“sourceMap”: true,
“experimentalDecorators”: true,
“emitDecoratorMetadata”: true,
“skipDefaultLibCheck”: true,
“strictNullChecks”: false,
“skipLibCheck”: true, // Workaround for https://github.com/angular/angular/issues/17863. Remove this if you upgrade to a fixed version of Angular.
“strict”: true,
“lib”: [ “es2015”, “es5”, “es2015.promise”, “dom” ],
“types”: [ “webpack-env” ]
},
“exclude”: [ “bin”, “node_modules” ],
“atom”: { “rewriteTsconfig”: false }
}
Good day, this works with only a single file, how can I multi select files in the same folder and upload to the api.
The API code is missing iteration. I used link with a for each (source: https://stackoverflow.com/questions/1760510/foreach-on-request-files?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa)
var files = Enumerable.Range(0, Request.Form.Files.Count)
.Select(i => Request.Form.Files[i]);
foreach (var file in files)
{
string folderName = “Upload”;
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim(‘”‘);
string fullPath = Path.Combine(newPath, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
}
return Json(“Upload Successful.”);
}
catch (System.Exception ex)
{
return Json(“Upload Failed: ” + ex.Message);
}