I am using MVC5 and Razor for my website.
My site should have function to upload an file (it would be text file like .txt or .doc , .docx etc.).
I've managed to save file to my database but have no idea how to read it nor how to display content of file (text).
My Applicant model:
public class Applicant
{
// Some irrelevant properties of applicant like name, gender etc.
[Display(Name = "CV: ")]
public virtual ICollection<File> uploadedFiles { get; set; }
}
My File model:
public class File
{
[Key]
public int fileID { get; set; }
public string fileName { get; set; }
public int applicantID { get; set; }
public byte[] Content { get; set; }
public string ContentType { get; set; }
public virtual Applicant Applicant { get; set; }
}
My controller POST method:
// POST: Prijava/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "irrelevant properties,uploadedFiles")] Applicant prijava, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var cv = new Models.File
{
fileName = Path.GetFileName(upload.FileName),
ContentType = upload.ContentType
};
using (var reader = new BinaryReader(upload.InputStream))
{
cv.Content = reader.ReadBytes(upload.ContentLength);
}
prijava.uploadedFiles = new List<Models.File> { cv };
ViewBag.Message = "File uploaded successfully";
}
else
{
ViewBag.Message = "File upload failed.";
}
}
}
For testing purpose uploaded .txt file contains text: "THIS IS TEST FILE !!!", in database file is stored like: "0x5448495320495320544553542046494C4520212121"
So I have my file written in binary to my database but have no clue how to display content in view and as an download.