0

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.

Kruno MONO
  • 81
  • 13
  • 1
    Why have you shown us code for controller method that you say works and has nothing to do with your question –  Dec 22 '16 at 00:29
  • If it's reading the binary into your database, than it's doing what you told it to. You need to go read about serialization and deserialization. You probably don't want to read it in as bytes, but rather deserialize it. – Scuba Steve Dec 22 '16 at 00:37
  • Because someone may find it helpful (way i found plenty of answers to my questions on this site) – Kruno MONO Dec 22 '16 at 00:40
  • Scuba Steve, is there a better way to store file in database than binary?? – Kruno MONO Dec 22 '16 at 00:42

0 Answers0