Reputation: 167
I'm new in asp.net core development, can someone please suggest me how to manage and upload files in my root/files folder.
Upvotes: 1
Views: 177
Reputation: 3195
You can use Request.Form.Files
to get the file from your request.
[HttpPost]
[Route("api/v1/doaitems/upload/{id:int}")]
public async Task<IActionResult> UploadFile(int id, [FromQuery] string distId, [FromQuery] string activity)
{
try
{
var file = Request.Form.Files[0];
string folderName = "Uploads";
string webRootPath = _env.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
int MaxContentLength = 1024 * 1024 * 2; //2 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf", ".xls", ".xlsx", ".doc", ".docx" };
if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
TempData["UploadFail"] = "Failed";
return RedirectToAction("failed", "failed");
}
else if (file.Length > MaxContentLength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
ViewBag.Message = "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB";
TempData["UploadFail"] = "Failed";
TempData["UploadSuccess"] = null;
return RedirectToAction("failed", "failed");
}
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(newPath, fileName);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);
string ext = Path.GetExtension(fullPath);
fileName = filenameWithoutExtension + "_" + DateTime.Now.ToString("MM-dd-yy") + ext;
fullPath = Path.Combine(newPath, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
await file.CopyToAsync(stream);
DocItem item = new DocItem
{
Name = fileName,
Description = fileName,
FileName = fileName,
FilePath = fullPath,
FileUri = folderName + "/" + fileName
};
await _dbContext.DocItems.AddAsync(item);
await _dbContext.SaveChangesAsync();
}
}
return Json("Upload Successful.");
}
catch (Exception ex)
{
return Json("Upload Failed: " + ex.Message);
}
}
Upvotes: 2