繁体   English   中英

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

[英]Download Blob as a file in ASP.NET MVC

我将文件保存为MySQL数据库为blob。 能帮帮我吗,我该怎么下载这个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; }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM