Link to home
Start Free TrialLog in
Avatar of j_arya
j_arya

asked on

Download Multiple Files with Asp.net

Hello guys,

I need one help. I have written a code for downloading files on a given link. Single file download is working properly. but i want to create a functionality for download all. User can check multiple files and then when he selects download button it should download all the selected files automatically.

regards,

My Current Code :

Dim strRequest() As String '= Request.QueryString("file") '-- if something was passed to the file querystring
        Dim i As Integer
        strRequest = Split("YServer.txt,PkgClnup.log", ",")
        For i = 0 To UBound(strRequest)
            Response.Write(Server.MapPath(strRequest(i)) & " : " & i)
            If strRequest(i) <> "" Then 'get absolute path of the file
                Dim path As String = Server.MapPath(strRequest(i)) 'get file object as FileInfo                
                'Dim file As System.IO.FileInfo = New System.IO.FileInfo(path) '-- if the file exists on the server

                Dim fs As FileStream
                fs = File.Open(path, FileMode.Open)
                Dim bytBytes(fs.Length) As Byte
                fs.Read(bytBytes, 0, fs.Length)
                fs.Close()

                Response.AddHeader("Content-Disposition", "attachment; filename=" & strRequest(i))
                'Response.AddHeader("Content-Length", File.Length.ToString())
                Response.ContentType = "APPLICATION/OCTET-STREAM"
                Response.Flush()
                Response.BinaryWrite(bytBytes)
                Response.Clear()
                Response.ClearHeaders()
                Response.ClearContent()
            Else
                Response.Write("Please provide a file to download.")
            End If
            Response.End() 'if file does not exist
        Next
Avatar of GavinMannion
GavinMannion

The only way I know how you are going to do this is to keep this code the same and call this page multiple times for multiple files.
r u not using a "file upload" control, the one with the "browse" button? if yes, then u could just add multiple controls .. as many as u want ..
Avatar of j_arya

ASKER

To Rejojohny,

No I dont want to Upload the files. The files are already uploaded. I want to download multiple files from a single link.
>>I want to download multiple files from a single link
what do u mean .. r the files present in the web server? can u pls give more explanation on what u r trying to do?
Avatar of j_arya

ASKER

There are files uploaded on webserver. there can be multiple files. the client has to select the files from a page. then click on download button. the code i have given is my download.aspx file. i have hardcoded 2 filenames which i want to download from the server. This is for Admin user of the site.
oh!! u mean the user has to downloadmultiple files from server .. the best way would be to provide hyperlinks to the selected files and the user can click on each file and download it ..
Avatar of j_arya

ASKER

Yes i have provided this utility. but i need this for admin user who can download multiple orders. and the orders they used to get is around 200 to 500 so it would be hard for him to click on every link and download the files. thats why i want to give him option to download multiple files.
so even if u manage to show 200 to 500 files in different browsers .. won't that be a problem for him .. with response.contenttype set the way u have .. he would be promted to save/open for each of those files .. maybe u have to think of another approach .. is this a intranet development .. then u could probably have a shared access in a different server i.e. which the webserver and the user can access .. then u can use system.IO to copy the selected file to that area ..

Rejo
Your other option running with Rejojohny's idea would be to use a zip component that a 3rd party offers and to zip all the files and download that one only?
Avatar of j_arya

ASKER

Yes, I am using that as last option. But the client has agreed to select 5-6 invoices at a time and download them. but he want to select them at once and then click download. he is okey with clicking on multiple file save dialog boxes
Then I would go with my other option.

When he clicks download, check how many documents are checked and open a new window for each document.

foreach(CheckBox on Page)
{
    if( CheckBox.IsChecked)
       RegisterStartUpScript("te"<script language='javascript'>window.open('Download.aspx?filename=' + CheckBox.text +')</script>");
}


That code won't compile but hopefully will give you the idea I am talking about
Avatar of j_arya

ASKER

let me try it... i think this should solve the problem
Avatar of j_arya

ASKER

its not working....i mean it opens different windows and the dialog box for download too. so the user has to close all the windows manually :(
Do the files download?

Then it is working... just not nicely :)

What you can do then is in your loop sleep the thread for a bit then redirect the window that is open using javascript to start the new download. I don't know how safe that is going to be though.

Avatar of j_arya

ASKER

i changed the code... this is my javascript code. but here also user has to close all the windows and all the windows are opening after timeout of 5 seconds.

function downloadSelected(){
                        var objCheckbox = document.getElementsByName("chkOrd")
                        for(var i=0; i<objCheckbox.length; i++){
                              if(objCheckbox[i].checked){
                                                                        window.setTimeout('OpenWindow("'+document.getElementsByName("chkOrd")(i).value+'")',5000);
                              }
                        }
                  }
                  function OpenWindow(FileName)            
                  {
                        window.open("DownloadFiles.aspx?FileName="+FileName,"mywnd"+FileName,"height=1,width=1");                  
                  }
Now instead of opening a new window open a named window. Then if the named window currently exists it should redirect it

Something along the lines of

if (myWin.closed)
      myWin = window.open("DownloadFiles.aspx?FileName="+FileName,"mywnd"+FileName,"height=1,width=1");
else
      myWin.location = "DownloadFiles.aspx?FileName="+FileName;
Avatar of j_arya

ASKER

These are my functions.. But the problem is it works for the first time for second time without refreshing the page when i click download button it gives me Javascript Error on the statement marked with XXXXXX.

function downloadSelected(){
                        var objCheckbox = document.getElementsByName("chkOrd")
                        var myWin='', str;
                        for(var i=0; i<objCheckbox.length; i++){
                              if(objCheckbox[i].checked){
                                    //window.open("DownloadFiles.aspx?FileName="+document.getElementsByName("chkOrd")(i).value,"mywnd"+i,"height=1,width=1");                                                                        
                                    window.setTimeout('OpenWindow('+myWin+',"'+document.getElementsByName("chkOrd")(i).value+'")',2000);
                              }
                        }
                  }
                  
                  function OpenWindow(myWin, FileName)            
                  {                                                
                        if(!myWin)
                        {                              
                              myWin = window.open("DownloadFiles.aspx?FileName="+FileName,"mywnd","height=400,width=500");                                                
                              //if (!myWin.opener) myWin.opener = self;
                              //if (window.focus) {myWin.focus()}                                                      
                        }
                        else
                        {
                              myWin.location = "DownloadFiles.aspx?FileName="+FileName; // XXXXXX                              
                        }
                  }
What is the javascritp error?

The one strange thing I am seeing is that you do not seem to name you child window?

You might also try myWin.document.location = "DownloadFiles.aspx?FileName=" + FileName;
Avatar of j_arya

ASKER

I have sorted out it differently....

function downloadSelected(){
                        var objCheckbox = document.getElementsByName("chkOrd")
                        var myWin='', str='';
                        for(var i=0; i<objCheckbox.length; i++){
                              if(objCheckbox[i].checked){                                    
                                    str = str + document.getElementsByName("chkOrd")(i).value + ",";
                              }
                        }
                        myWin = window.open("DownloadFiles.asp?Args="+str,"myWindow","height=400,width=400");
                  }

Called an ASP file. in that ASP files i created framesets and gave its source as the files to be downloaded...


<%
      Args = Request.QueryString("Args")
      FileNames = split(Args,",")
      ColWidth = Int(100 / (Ubound(FileNames)))
      str=""
      for i=0 to ubound(FileNames)-1
            'response.Write i & " : " & FileNames(i) & "<br>"
            str=str & colWidth & "%,"
      next
      str = mid(str,1,len(str)-1)
%>
<html>
<head>
<title>Download Files</title>
</head>
<frameset rows="0,*">
<frameset cols="<%=str%>">      
<%
      for i=0 to ubound(FileNames) - 1
            strFileName = "../images/orders/" & FileNames(i) & ".zip"
%>                  
                  <frame src="<%=strFileName%>" >
                  
<%
      next
%>      
</frameset>
</frameset>
</html>
Hey that is a different way of doing it :)

I can think of no good reason why that solution would not work in the long run......
ASKER CERTIFIED SOLUTION
Avatar of GranMod
GranMod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial