Popular Posts

Wednesday, 26 February 2014

UPLOAD AND DOWNLOAD MULTIPLE FILES WITH SIMPLE JAVASCRIPT

UPLOAD AND DOWNLOAD MULTIPLE FILES WITH SIMPLE JAVASCRIPT


DESIGN PAGE:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
    .fileUpload{
    width:255px;    
    font-size:11px;
    color:#000000;
    border:solid;
    border-width:1px;
    border-color:#7f9db9;    
    height:17px;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div id="fileUploadarea"><asp:FileUpload ID="fuPuzzleImage" runat="server" CssClass="fileUpload" /><br /></div><br />
    <div><input style="display:block;" id="btnAddMoreFiles" type="button" value="Add more images" onclick="AddMoreImages();" /><br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button2" runat="server" Text="SHOW FILES" 
            onclick="Button2_Click" />
        &nbsp;&nbsp;&nbsp;&nbsp;
        <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

        </div>
        <div id="download" runat="server">
        
      <p>  ALL AVAILABEL FILES :<br /></p>
      <br />
        
        </div>
    </div>
    <script language="javascript" type="text/javascript">
        function AddMoreImages() {
            if (!document.getElementById && !document.createElement)
                return false;
            var fileUploadarea = document.getElementById("fileUploadarea");
            if (!fileUploadarea)
                return false;
            var newLine = document.createElement("br");
            fileUploadarea.appendChild(newLine);
            var newFile = document.createElement("input");
            newFile.type = "file";
            newFile.setAttribute("class", "fileUpload");

            if (!AddMoreImages.lastAssignedId)
                AddMoreImages.lastAssignedId = 100;
            newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
            newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
            var div = document.createElement("div");
            div.appendChild(newFile);
            div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
            fileUploadarea.appendChild(div);
            AddMoreImages.lastAssignedId++;
        }
   
    </script>
    </form>
</body>
</html>




Here we are adding asp control upload dynamically (up to max 6 optionally) on btnAddMoreFiles button click and call the java script  function AddMoreImages .

Button2 Is used to list all the files been upoaded successfully . 



CODE BEHIND PAGE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Threading;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
       }
  protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            Label1.Text = "";
            HttpFileCollection hfc = Request.Files;
            
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    string type = hpf.FileName.Split(".".ToCharArray())[1].ToString();
                    if (type == "doc" || type == "docx" || type == "DOC" || type == "DOCX")
                    {
                        if (hpf.ContentLength > 0 && hpf.ContentLength < 5242880)
                        {
                            hpf.SaveAs(Server.MapPath("~/uploads/") + System.IO.Path.GetFileName(hpf.FileName));
                            Label1.Text += "<br/>file "+ hpf.FileName+" uploaded successfully...<br/>";

                        }
                        else
                        {

                            Label1.Text += "FILE of size more than 5 mb ("+hpf.FileName+") are not allowed<br />";
                        }
                    }
                    else
                    {

                        Label1.Text += "only docs file are allowed"+hpf.FileName+" NOT UPLOADED";
      
                    
                    }
                   
                }
           
               
        }
        catch (Exception)
        {
            
            throw;
        } 
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/uploads"));
        int i = 0;
        foreach (FileInfo fi in di.GetFiles())
        {
            HyperLink HL = new HyperLink();
            HL.ID = "HyperLink" + i++;
            HL.Text = fi.Name;
            HL.NavigateUrl = "Download.aspx?file=" + fi.Name;
            download.Controls.Add(HL);
            download.Controls.Add(new LiteralControl("<br/>"));
        }
    }
    }



HERE I have made a restriction that only doc files will be uploaded and of size less than 5 mb.
it depends upon you what are the conditions.
 
On button2_Click the files been uploaded are shown in hyperlink and on clicking the hyper link the file are been downloaded.


BELOW IS THE CODE FOR DOWNLOAD FILE:


using System.IO;
using System.Threading;

public partial class Download : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string filename = Request["file"].ToString();
        fileDownload(filename, Server.MapPath("~/uploads/" + filename));
    }
    private void fileDownload(string fileName, string fileUrl)
    {
        Page.Response.Clear();
        bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
        if (!success)
            Response.Write("Downloading Error!");
        Page.Response.End();

    }
    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                int pack = 10240; //10K bytes
                int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }