Reputation: 216
I am saving the uploaded file content as byte array with file extension in database. I wanted to use file result which returns any type of file. How can i achieve it ?
I tried with image file. Can i do like below code for all types ? will that works ?
public ActionResult GetAttachmentById(int AttachmentId)
{
try
{
byte[] AttachmentData = GetFromDatabase(AttachmentId);
string FileExtension = GetExtensionFromDatabase(AttachmentId);
return File(AttachmentData, FileExtension );
}
catch (Exception ex)
{
return File("", FileExtension);
}
}
Upvotes: -1
Views: 2593
Reputation: 3246
You need to define the Mimetype, file name and extension dynamically.
Then return a File object from the action like this:
string filename = "MyFile.txt"; // Make this dynamic from the actual file
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(filedata, contentType);
Upvotes: 1