【问题标题】:Download Blob as a file in ASP.NET MVC在 ASP.NET MVC 中将 Blob 下载为文件
【发布时间】:2019-04-05 18:10:23
【问题描述】:

我正在将一个文件作为 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; }
}

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    相关资源
    最近更新 更多