Скачать Varbinary из sql кусками - PullRequest
2 голосов
/ 14 марта 2019

Как мне использовать пример кода ниже для загрузки из таблицы SQL в c #?

public static void DownloadLargeFile(string DownloadFileName, string FilePath, string ContentType, HttpResponse response)
        {
            Stream stream = null;

            // read buffer in 1 MB chunks
            // change this if you want a different buffer size
            int bufferSize = 1048576;

            byte[] buffer = new Byte[bufferSize];

            // buffer read length
            int length;
            // Total length of file
            long lengthToRead;

            try
            {
                // Open the file in read only mode 
                stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);

                // Total length of file
                lengthToRead = stream.Length;
                response.ContentType = ContentType;
                response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(DownloadFileName, System.Text.Encoding.UTF8));

                while (lengthToRead > 0)
                {
                    // Verify that the client is connected.
                    if (response.IsClientConnected)
                    {
                        // Read the data in buffer
                        length = stream.Read(buffer, 0, bufferSize);

                        // Write the data to output stream.
                        response.OutputStream.Write(buffer, 0, length);

                        // Flush the data 
                        response.Flush();

                        //buffer = new Byte[10000];
                        lengthToRead = lengthToRead - length;
                    }
                    else
                    {
                        // if user disconnects stop the loop
                        lengthToRead = -1;
                    }
                }
            }
            catch (Exception exp)
            {
                // handle exception
                response.ContentType = "text/html";
                response.Write("Error : " + exp.Message);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                response.End();
                response.Close();
            }
        }

Я не могу понять это. Я не могу понять, как вернуть Varbinary в FileStream. Загрузка моего файла Varbinary завершится неудачно, если размер файла превышает 40 МБ. Я могу заставить этот код работать для загрузки с файлового сервера, но не для SQL Varbinary.

Ниже приведено то, что я сейчас использую, но я получаю Network-Failure для любого файла размером более 40 МБ. Я пытаюсь выяснить, как бы я реализовал загрузку кусками байтов для этого кода.

protected void lnkDownloadIR_Click(object sender, EventArgs e)
        {

            LinkButton lnkbtn = sender as LinkButton;
            GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
            int id = Convert.ToInt32(gvrow.Cells[2].Text);
            byte[] bytes;
            string fileName, contentType;
            Int64 fileSizeInBytes;
            string constr = ConfigurationManager.ConnectionStrings["OCMCA_CEConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "SELECT FileName, FileData, ContentType FROM InstructorResources where Id=@Id";
                    cmd.Parameters.AddWithValue("@Id", id);
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        sdr.Read();
                        bytes = (byte[])sdr["FileData"];
                        contentType = sdr["ContentType"].ToString();
                        fileName = sdr["FileName"].ToString();

                    }
                    con.Close();
                }
            }
            Response.Clear();
            Response.Buffer = true;
            Response.BufferOutput = false;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = contentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            fileSizeInBytes = bytes.Length;
            Response.AddHeader("Content-Length", fileSizeInBytes.ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }

Спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...