将Blob下载为ASP.NET MVC中的文件

时间:2019-04-05 18:10:23

标签: c# asp.net ajax asp.net-mvc

我正在将文件作为blob保存到MySQL数据库。您能帮我吗,我如何将这个Blob下载为文件?我的数据库中有Blob数据和ContentType。您可以在下面查看我的下载方法。我已经搜索了一个多星期,但无法成功。我也不知道我可以直接通过方法下载,还是需要编写ajax。非常感谢您的帮助和协助。非常感谢!

方法:

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;
    }
}

班级

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 个答案:

答案 0 :(得分:0)

非常感谢您的回答!我找到了解决方案,并在下面编写代码块。

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;
        }
    }