Exemplo n.º 1
0
        public static void DownloadFile(int fileId, HttpResponse response, bool AddContentDispositionHeader)
        {
            string fileName;
            string contentType;
            int    size;

            GetInfo(fileId, out fileName, out contentType, out size);

            response.ContentType = contentType;

            string susag = HttpContext.Current.Request.UserAgent.ToString();

            if (susag.IndexOf("MSIE") > 0)
            {
                string sextension = "";
                string _fileName  = fileName;
                int    lastDot    = fileName.LastIndexOf(".");
                if (lastDot >= 0)
                {
                    sextension = fileName.Substring(lastDot);
                    _fileName  = fileName.Substring(0, lastDot);
                }
                bool MoreThan127 = false;
                for (int i = 0; i < _fileName.Length; i++)
                {
                    char ch = _fileName[i];
                    int  j  = (int)ch;
                    if (j > 127)
                    {
                        MoreThan127 = true;
                        break;
                    }
                }
                if (MoreThan127 && _fileName.Length > 25)
                {
                    _fileName = _fileName.Substring(0, 25);
                }
                fileName = HttpContext.Current.Server.UrlPathEncode(_fileName + sextension);
            }

            if (AddContentDispositionHeader)
            {
                response.AddHeader("content-disposition", String.Format("attachment; filename=\"{0}\"", fileName));
            }

            const int iBufferSize = 65536;             // 64 KB

            byte[] outbyte = new byte[iBufferSize];

            using (IDataReader reader = DBFile.GetBinaryData(fileId))
            {
                if (reader != null)
                {
                    if (reader.Read())
                    {
                        long read = 0, startIndex = 0;
                        do
                        {
                            if (response.IsClientConnected)
                            {
                                read = reader.GetBytes(0, startIndex, outbyte, 0, iBufferSize);
                                response.OutputStream.Write(outbyte, 0, System.Convert.ToInt32(read));
                                response.Flush();
                                startIndex += read;
                            }
                            else
                            {
                                read = 0;
                            }
                        } while(read == iBufferSize);
                    }
                }
            }
        }