Click here to Skip to main content
15,306,245 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
int nFileLen;
string sFilename;
HttpPostedFile myFile;
    private void Page_Load(object sender, System.EventArgs e)
    {
        // Put user code to initialize the page here
        lblStoredLoc.Visible = false;
        if (imgPicture.ImageUrl.ToString() == string.Empty)
        {
            imgPicture.Visible = false;
        }
    }
    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }
    public void URLPth(string Path)
    {
        lblStoredLoc.Text = Path;

    }
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
        this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    private void btnUpload_Click(object sender, System.EventArgs e)
    {
        // If file field isn’t empty
        if (filUpload.PostedFile != null)
        {
            // Check file size (mustn’t be 0)
            myFile = filUpload.PostedFile;
            nFileLen = myFile.ContentLength;
            if (nFileLen == 0)
            {
                lblOutput.Text = "There wasn't any file uploaded.";
                return;
            }
            // Check file extension (must be bmp)
            if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".bmp")
            {
                lblOutput.Text = "The file must have an extension of bmp";
                return;
            }
            SaveFile(nFileLen,myFile);
        }
    }
    public void SaveFile(int nFileLen, HttpPostedFile myFile)
    {
        // Read file into a data stream
        byte[] myData = new Byte[nFileLen];
        myFile.InputStream.Read(myData, 0, nFileLen);
        // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an incremental numeric until it is unique
        sFilename = System.IO.Path.GetFileName(myFile.FileName);
        int file_append = 0;
        while (System.IO.File.Exists(Server.MapPath(sFilename)))
        {
            file_append++;
            sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + ".bmp";
        }
        // Save the stream to disk
        System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sFilename), System.IO.FileMode.Create);
        newFile.Write(myData, 0, myData.Length);
        newFile.Close();
        // Check whether the file is really a BMP by opening it
        System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
        Bitmap myBitmap;
        try
        {
            myBitmap = new Bitmap(Server.MapPath(sFilename));
            // Set the image name
            URLPth(sFilename.ToString());
            imgPicture.ImageUrl = sFilename;
            if (imgPicture.ImageUrl.ToString() != string.Empty)
            {
                imgPicture.Visible = true;
            }
            // Displaying success information
            lblOutput.Text = "File uploaded successfully!";
            // Destroy objects
            myBitmap.Dispose();
        }
        catch (ArgumentException errArgument)
        {
            // The file wasn't a valid bmp file
            lblOutput.Text = "There wasn't a valid file to upload.";
            System.IO.File.Delete(Server.MapPath(sFilename));
        }
    }
    public bool ThumbnailCallback()
    {
        return false;
    }
    protected void btnDownload_Click1(object sender, EventArgs e)
    {
        if (lblStoredLoc.Text != string.Empty)
        {
            Download();
        }
        else
        {
            lblOutput.Text = "Please choose a file to upload first";
            return;
        }
    }
    private bool Download()
    {
        //File Path and File Name
        string filePath = Server.MapPath(lblStoredLoc.Text);
        System.IO.FileInfo FileName = new System.IO.FileInfo(filePath);
        FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        //Reads file as binary values
        BinaryReader _BinaryReader = new BinaryReader(myFile);
        //Check whether file exists in specified location
        if (FileName.Exists)
        {
            try
            {
                long startBytes = 0;
                string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
                string _EncodedData = HttpUtility.UrlEncode(lblStoredLoc.Text, Encoding.UTF8) + lastUpdateTiemStamp;
                Response.Clear();
                Response.Buffer = false;
                Response.AddHeader("Accept-Ranges", "bytes");
                Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
                Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName.Name);
                Response.AddHeader("Content-Length", (FileName.Length - startBytes).ToString());
                Response.AddHeader("Connection", "Keep-Alive");
                Response.ContentEncoding = Encoding.UTF8;
                //Send data
                _BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                //Dividing the data in 1024 bytes package
                int maxCount = (int)Math.Ceiling((FileName.Length - startBytes + 0.0) / 1024);
                //Download in block of 1024 bytes
                int i;
                for (i = 0; i < maxCount && Response.IsClientConnected; i++)
                {
                    Response.BinaryWrite(_BinaryReader.ReadBytes(1024));
                    Response.Flush();
                }
                //if blocks transfered not equals total number of blocks
                if (i < maxCount)
                    return false;
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                Response.End();
                _BinaryReader.Close();
                myFile.Close();
            }
        }
        else System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(),"FileNotFoundWarning", "alert('File is not available now!')", true);
        return false;
    }



XML
<body>
    <form id="form1" runat="server" oncontextmenu="return false">

        <table class="style1" width="100%">
            <tr align="left">
                <td colspan="3">
    <asp:FileUpload ID="filUpload" runat="server" BackColor="White" Font-Bold="True"
                        Font-Names="Calibri" Font-Size="18pt" ForeColor="#3399FF"
                        ToolTip="Choose a file" />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
       <asp:Label ID="lblStoredLoc" runat="server"></asp:Label>
                </td>
            </tr>
            <tr align="left">
                <td class="style4" align="center">
        <asp:Button ID="btnUpload" runat="server" Text="Upload" BackColor="#6699FF"
                        Font-Bold="True" Font-Names="Calibri" Font-Size="18pt" ForeColor="White"
                        Height="50px" ToolTip="Upload" Width="150px" BorderStyle="None"
                        onclick="btnUpload_Click1" />
                </td>
                <td class="style5" align="center">
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:Label ID="lblOutput" runat="server" Font-Bold="True" Font-Names="Calibri"
                        Font-Size="18pt" ForeColor="#3366FF"></asp:Label>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;
                </td>
                <td class="style3" align="center">
        <asp:Button ID="btnDownload" runat="server" Text="Download"
            onclick="btnDownload_Click1" BackColor="#66CCFF" Font-Bold="True" Font-Names="Calibri"
                        Font-Size="18pt" ForeColor="Black" Height="50px" Width="150px"
                        BorderStyle="None" />
                </td>
            </tr>
            <tr align="center">
                <td colspan="3">
        <asp:Image ID="imgPicture" runat="server" />
                </td>
            </tr>
        </table>

    </form>
</body>


[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 2-Jun-11 23:33pm
v2
Comments
OriginalGriff 3-Jun-11 5:33am
   
I added the code block for you, but you forgot the question!
What is it you wanted to know?
R. Giskard Reventlov 3-Jun-11 8:46am
   
Too much code: ask a question and include only a relevant code snippet: no one wants to wade through that lot.
   
Not a question.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900