简体   繁体   中英

Download a .zip file from database using C# Ado.net

I have a .zip file in the database (BLOB). I want to retrieve the same in my api. Please find below code snippet. I am able to download a zip file but not able to extract it. getting an error while extracting.

public IHttpActionResult GetDownloadLetter()
{
    DownloadDocument docInfo = blogicObj.DownloadLetter();
    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(docInfo.Document.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = docInfo.DocumentName + ".zip"
    };

    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    var response = ResponseMessage(result);
    return response;
}


public class DownloadDocument
{
    public MemoryStream Document { get; set; }
    public string DocumentType { get; set; }
    public string DocumentName { get; set; }
}

public DownloadDocument DownloadDocument()
{
    DownloadDocument letter = null;
    try
    {
        letter = GetDummyDownload();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return letter;
}

public MemoryStream GetMemoryStream(SqlDataReader reader, int columnIndex)
{
    using (MemoryStream stream = new MemoryStream())
    {
        long startIdx = 0;
        byte[] buffer = new byte[256];

        while (true)
        {
            long retBytes = reader.GetBytes(columnIndex, startIdx, buffer, 0, buffer.Length);
            stream.Write(buffer, 0, (int)retBytes);
            startIdx += retBytes;
            if (retBytes != buffer.Length)
                break;
        }
        return stream;
    }
}

public DownloadDocument GetDummyDownload()
{
    DownloadDocument letter = null;
    string strQuery = "select * from [dbo].[documents] where id=1";

    using (SqlConnection connection = new SqlConnection(connStr))
    {
        SqlCommand command = new SqlCommand(connStr);
        command.CommandType = CommandType.Text;
        command.CommandText = strQuery;
        command.Connection = connection;
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        // Call Read before accessing data.
        while (reader.Read())
        {
            letter = new DownloadDocument();
            letter.Document = GetMemoryStream(reader, 4); //4 is for document column
            letter.DocumentType = Convert.ToString(reader["DocumentType"]);
            letter.DocumentName = Convert.ToString(reader["Name"]);
        }
        // Call Close when done reading.
        reader.Close();
    }
    return letter;
}

Your C# application can use J# library to extract zip file. It's basically Java library:

using(var fis = new java.io.FileInputStream(FileName))
{
    using(var zis = new java.util.zip.ZipInputStream(fis))
    {
        java.util.zip.ZipEntry ze;
        while((ze = zis.getNextEntry()) != null)
        {
            if (ze.isDirectory())
                continue;

            Console.WriteLine("File name: " + ze.getName());
        }
    }
}
public IHttpActionResult GetDownloadLetter()
{
    DownloadDocument docInfo = blogicObj.DownloadLetter();
    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(docInfo.Document.ToArray())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = docInfo.DocumentName + ".zip"
    };

    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    var response = ResponseMessage(result);
    return response;
}


public class DownloadDocument
{
    public MemoryStream Document { get; set; }
    public string DocumentType { get; set; }
    public string DocumentName { get; set; }
}

public DownloadDocument DownloadDocument()
{
    DownloadDocument letter = null;
    try
    {
        letter = GetDummyDownload();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return letter;
}

public MemoryStream GetMemoryStream(SqlDataReader reader, int columnIndex)
{
      byte[] buffer = (byte[])reader.GetValue(columnIndex);
            MemoryStream stream = new MemoryStream(buffer);
            return stream;
}

public DownloadDocument GetDummyDownload()
{
    DownloadDocument letter = null;
    string strQuery = "select * from [dbo].[documents] where id=1";

    using (SqlConnection connection = new SqlConnection(connStr))
    {
        SqlCommand command = new SqlCommand(connStr);
        command.CommandType = CommandType.Text;
        command.CommandText = strQuery;
        command.Connection = connection;
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        // Call Read before accessing data.
        while (reader.Read())
        {
            letter = new DownloadDocument();
            letter.Document = GetMemoryStream(reader, 4); //4 is for document column
            letter.DocumentType = Convert.ToString(reader["DocumentType"]);
            letter.DocumentName = Convert.ToString(reader["Name"]);
        }
        // Call Close when done reading.
        reader.Close();
    }
    return letter;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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