Tuesday, February 12, 2013

SharePoint : Downloading a file from document library without writing to disk

I needed to code to download a file from a document library without writing to the physical drive. I have a PDF icon in one of the web parts which is referred to Download.aspx in _LAYOUTS folder. In the Page_Load event of the file is the following function to download the document and for a prompt without writing to the drive. This method uses SPFile.OpenBinary() method to get bytes.

private void Downloadfile()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = currentSite.OpenWeb(SPContext.Current.Web.ID))
                        {
                            web.AllowUnsafeUpdates = true;
                            string strContentType = "";

                            SPList list = web.Lists["DocumentLibraryName"];
                            string fileName = "FileNameToDownload.pdf";
                            SPFile file = web.Lists["DocumentLibraryName"].RootFolder.Files[fileName];

                            string[] fullFileName = fileName.Split('.');
                            int len = fullFileName.Length;
                            
                            byte[] fileContents = (byte[])file.OpenBinary();
                            
                            //Prepare a content type based on file extension name
                            string fileExtension = fullFileName[len - 1].ToString();
                            switch (fileExtension)
                            {
                                case "txt":
                                    strContentType = "text/plain";
                                    break;
                                case "htm":
                                    strContentType = "text/html";
                                    break;
                                case "html":
                                    strContentType = "text/html";
                                    break;
                                case "rtf":
                                    strContentType = "text/richtext";
                                    break;
                                case "jpg":
                                    strContentType = "image/jpeg";
                                    break;
                                case "jpeg":
                                    strContentType = "image/jpeg";
                                    break;
                                case "gif":
                                    strContentType = "image/gif";
                                    break;
                                case "bmp":
                                    strContentType = "image/bmp";
                                    break;
                                case "mpg":
                                    strContentType = "video/mpeg";
                                    break;
                                case "mpeg":
                                    strContentType = "video/mpeg";
                                    break;
                                case "avi":
                                    strContentType = "video/avi";
                                    break;
                                case "pdf":
                                    strContentType = "application/pdf";
                                    break;
                                case "doc":
                                    strContentType = "application/msword";
                                    break;
                                case "dot":
                                    strContentType = "application/msword";
                                    break;
                                case "csv":
                                    strContentType = "application/vnd.msexcel";
                                    break;
                                case ".xls":
                                    strContentType = "application/vnd.msexcel";
                                    break;
                                case ".xlt":
                                    strContentType = "application/vnd.msexcel";
                                    break;
                                default:
                                    strContentType = "application/octet-stream";
                                    break;
                            }

                            //Do not buffer
                            this.Page.Response.Buffer = false;

                            this.Page.Response.ClearContent();
                            this.Page.Response.ClearHeaders();
                            this.Page.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName.ToString());
                            this.Page.Response.ContentType = strContentType;

                            //Check that the client is connected and has not closed the connection after the request
                            if (this.Page.Response.IsClientConnected)
                            {
                                this.Page.Response.BinaryWrite(fileContents);
                            }

                            //No need to flush or close as buffering is disabled
                            //this.Page.Response.Flush();
                            //this.Page.Response.Close();
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


No comments:

Post a Comment