I am saving a file to MySQL database as blob. Could you please help me, how can I download this blob as a file? I have blob data and ContentType in the database. You can see my method for downloading below. I have been searching for over a week, but I couldn't make it. I also don't know that I can download directly over method or I need to write ajax. I highly appreciate your help and assistance. Thanks a lot!

Method:

public HttpPostedFileBase Indir()
{
    using (ISession session=FluentNHibernateHelper.OpenSession())
    {
        var doc = new Document();
        var docDet = new DocumentDetail();

        doc = session.Query<Document>().FirstOrDefault(x => x.Id == 5);
        docDet = session.Query<DocumentDetail>().FirstOrDefault(x => x.DocumentId == doc.Id);

        var test = new MemoryPostedFile(docDet.File, doc.DocumentName, doc.DocumentExtention);
        return test;
    }
}

Class:

public class MemoryPostedFile:HttpPostedFileBase
{
    private readonly byte[] fileBytes;

    public MemoryPostedFile(byte[] fileBytes, string fileName = null, string ContentType = null)
    {
        this.fileBytes = fileBytes;
        this.FileName = fileName;
        this.ContentType = ContentType;
        this.InputStream = new MemoryStream(fileBytes);
    }

    public override int ContentLength => fileBytes.Length;

    public override string FileName { get; }
    public override string ContentType { get; }
    public override Stream InputStream { get; }
}

1 Answers

0
CraexIt On Best Solutions

Thank you so much for your answers! I found the solution and I am writing the code block below.

public HttpPostedFileBase Indir(string documentId)
    {
       using (ISession session=FluentNHibernateHelper.OpenSession())
        {

            var doc = new Document();
            var docDet = new DocumentDetail();

            doc = session.Query<Document>().FirstOrDefault(x => x.Id == Convert.ToInt32(documentId));
            docDet = session.Query<DocumentDetail>().FirstOrDefault(x=>x.DocumentId==doc.Id);
            var test = new MemoryPostedFile(docDet.File,doc.DocumentName,doc.DocumentExtention);
            Response.Clear();
            Response.ContentType = doc.DocumentExtention;//"application/octet-stream";
            Response.AddHeader("Content-Disposition","attachment; filename="+test.FileName+";");
            Response.BinaryWrite(docDet.File);
            Server.MapPath("~/"+test.FileName);
            Response.End();
            return test;
        }
    }