I want the file that I uploaded in the documentUploadProvinceLevels
database table to be able to be downloaded and to be saved in a special wwwroot
folder after downloading. I implemented the file upload part, but I don't know what to do for downloading.
please help me
Upload code:
public bool UploadAvatarProvinceDB(IFormFile file, RegisterViewModel document)
{
if (file != null)
{
if (file.Length > 0)
{
int department = 1;
document.uploadDate = DateTime.Now;
document.fileName = "no-document";
document.description = "ثبت تصویر پرسنل";
var docName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(docName);
var newFileName = String.Concat(document.nationalCode, fileExtension);
var objfiles = new DocumentUploadProvinceLevel()
{
id = 0,
fileName = newFileName,
uploadDate = DateTime.Now,
title = "تصویر پرسنل",
fileFormat = fileExtension,
userId = document.nationalCode,
description = document.description,
department = department,
IsDelete=false
};
using (var target = new MemoryStream())
{
file.CopyTo(target);
objfiles.dataBytes = target.ToArray();
}
_context.documentUploadProvinceLevels.Add(objfiles);
_context.SaveChanges();
return true;
}
}
return false;
}
documentUploadProvinceLevels
table:
You can use FileStream
. Below is a working demo, you can refer to it.
public async Task<bool> Download(int id)
{
byte[] bytes;
var item = _context.documentUploadProvinceLevels.Where(d => d.id == id).FirstOrDefault();
if (item != null)
{
var fileName = item.fileName;
bytes = item.dataBytes;
var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\files", fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await fileStream.WriteAsync(bytes);
}
return true;
}
return false;
}
Test Result: