Загрузить SWF-файл в ASP.NET - PullRequest
       4

Загрузить SWF-файл в ASP.NET

0 голосов
/ 12 февраля 2011

Я застрял с загрузкой SWF на моем ASPX. Я должен получить SWF из базы данных и отобразить на странице. Мой код удается создать SWF-файл в локальной папке после извлечения из базы данных ... но я не могу отобразить его на aspx автоматически после загрузки ... и какой код в aspx должен быть кстати? ... Есть идеи, ребята? ... THX ...

 public string swfFileName = "";


protected void Page_Load(object sender, EventArgs e)
{
    string swfToDbConnStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
    try
    {

        using (SqlConnection connection = new SqlConnection(swfToDbConnStr))
        {
            // Assumes that connection is a valid SqlConnection object.
            SqlCommand command = new SqlCommand(
              "SELECT gameStorage FROM eGame", connection);

            // Writes the BLOB to a file (*.swf).
            FileStream stream;
            // Streams the BLOB to the FileStream object.
            BinaryWriter writer;

            // Size of the BLOB buffer.
            int bufferSize = 100;
            // The BLOB byte[] buffer to be filled by GetBytes.
            byte[] outByte = new byte[bufferSize];
            // The bytes returned from GetBytes.
            long retval;
            // The starting position in the BLOB output.
            long startIndex = 0;



            // Open the connection and read data into the DataReader.
            connection.Open();
            SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess);

            while (reader.Read())
            {


                // Create a file to hold the output.
                stream = new FileStream(
                    //"logo" + pubID + ".swf", FileMode.OpenOrCreate, FileAccess.Write);
                "FBIS" + ".swf", FileMode.OpenOrCreate, FileAccess.Write);
                writer = new BinaryWriter(stream);

                // Reset the starting byte for the new BLOB.
                startIndex = 0;

                // Read bytes into outByte[] and retain the number of bytes returned.
                retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize);




                // Continue while there are bytes beyond the size of the buffer.
                while (retval == bufferSize)
                {

                    writer.Write(outByte);
                    writer.Flush();

                    // Reposition start index to end of last buffer and fill buffer.
                    startIndex += bufferSize;
                    retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize);
                }

                // Write the remaining buffer.
                writer.Write(outByte, 0, (int)retval - 1);
                writer.Flush();

                // Close the output file.
                writer.Close();
                stream.Close();

            }

            // Close the reader and the connection.
            reader.Close();
            connection.Close();
            swfFileName = Directory.GetCurrentDirectory();







        }
    }
    catch (Exception exs) { }
}

Ответы [ 2 ]

0 голосов
/ 13 февраля 2011

Чтобы отобразить файл SWF на странице, вам необходим флэш-объект для его загрузки. Затем вы должны указать объект flash на обработчик ASHX, который получит файл из базы данных и вернет его.

0 голосов
/ 13 февраля 2011

Чтение содержимого FILESTREAM с помощью SqlDataReader неэффективно, даже при использовании CommandBevavior.SequentialAccess.Вы делаете буферизованную копию, но вместо этого рассмотрите возможность использования Stream.CopyTo .Объявление потока через SqlDataReader тривиально, см. Загрузка и выгрузка изображений с SQL Server через ASP.Net MVC для примера кода, выполняющего именно это.

В целом, хотя с BLOB-объектами FILESTREAM,гораздо лучше просто использовать SqlFileStream, специально для большого контента.См. FILESTREAM MVC: Загрузка и выгрузка изображений с SQL Server для полной выборки, включая как загрузку, так и загрузку больших BLOB-объектов через ASP.Net.

В качестве примечания, чтение в файл простовернуть этот временный файл может быть довольно дорого, в зависимости от частоты доступа.

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