I am trying to build a file upload with the aspnetboilerplate .net core and angular spa. I am new to the framework and really like it but can't get the file upload working.
First if this can be done in a service without a controller that would be my preferred solution.
Currently I am trying a controller with the code below but it doesn't work
Here is .ts component method to upload file.
upload(files) {
if (files.length === 0)
return;
const formData = new FormData();
for (let file of files)
formData.append(file.name, file);
const uploadReq = new HttpRequest('POST', `api/FileUpload/UploadFile`, formData, {
reportProgress: true,
});
this.http.request(uploadReq).subscribe(event => {
if (event.type === HttpEventType.UploadProgress)
this.progress = Math.round(100 * event.loaded / event.total);
else if (event.type === HttpEventType.Response)
this.reqMessage = event.body.toString();
});
}
I put the controller in the myapp web host controller folder (The same folder where the antiforgery controller exist)
Here is my controller
[Route("api/[controller]")]
[ApiController]
public class FileUploadController : myappControllerBase
{
private IHostingEnvironment _hostingEnvironment;
public FileUploadController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpPost, DisableRequestSizeLimit]
public ActionResult UploadFile()
{
try
{
var file = Request.Form.Files[0];
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);
}
}
}
Not sure if the formData is setup correct but it does not reach my controller.