I'm loading images which are store in the database and I want to upload them to the serverpath which is in wwwroot folder.
byte[] imageData= //Loading image from sql server
string strWebPath = _hostingEnvironment.WebRootPath "\\img\\ "This is where I want to upload that image"";
How can I upload that image into wwwroot/img folder
CodePudding user response:
Storing image datas in the database is not the best way.
Anyway, if you have your image data in a byte array, you can store it anywhere using a filestream.
You need to add : using:System.IO;
byte[] imageData = ...//Loading image from sql server
string strWebPath = _hostingEnvironment.WebRootPath "\\img\\myImageName.png"; //yourImageName.Extension;
//You may have to change the FileMode.Create according the image names if, unique etc.
using (FileStream fs = new FileStream(strWebPath, FileMode.Create))
{
//Takes a byte array, writes to the disk from the given index until the given length.
fs.Write(imageData, 0, imageData.Length);
fs.Flush();
}
I hope this helps.
CodePudding user response:
In most cases, files are stored in the database as byte[]. So you can use this method to achieve it.
FileModel:
public class AppFile
{
public int Id { get; set; }
public string FileName { get; set; }
public byte[] Content { get; set; }
}
Method:
public async Task Uploadfilefromdb(int id)
{
//select file by id
var result =await _dbcontext.File.FirstOrDefaultAsync(x => x.Id == id);
var fileName = Path.GetFileName(result.FileName);
var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images",fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
//convert byte[] to IformFile
var stream = new MemoryStream(result.Content);
IFormFile file = new FormFile(stream, 0, result.Content.Length, "name", fileName);
await file.CopyToAsync(fileStream);
}
}
Demo:
After I use this method, image has been uploaded from database to wwwroot
.