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
j_aryaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GavinMannionCommented:
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.
0
RejojohnyCommented:
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 ..
0
j_aryaAuthor Commented:
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.
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

RejojohnyCommented:
>>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?
0
j_aryaAuthor Commented:
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.
0
RejojohnyCommented:
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 ..
0
j_aryaAuthor Commented:
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.
0
RejojohnyCommented:
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
0
GavinMannionCommented:
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?
0
j_aryaAuthor Commented:
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
0
GavinMannionCommented:
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
0
j_aryaAuthor Commented:
let me try it... i think this should solve the problem
0
j_aryaAuthor Commented:
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 :(
0
GavinMannionCommented:
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.

0
j_aryaAuthor Commented:
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");                  
                  }
0
GavinMannionCommented:
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;
0
j_aryaAuthor Commented:
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                              
                        }
                  }
0
GavinMannionCommented:
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;
0
j_aryaAuthor Commented:
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>
0
GavinMannionCommented:
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......
0
GranModCommented:
PAQed with points refunded (500)

GranMod
Community Support Moderator
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.