简体   繁体   中英

How to download multiple files on a single zip built on demand (using c# or javascript)

I'm struggling achieving a solution to download multiple files at once on my web site.

I've tried a client approach but it didn't work because the files I want to open are images and it doesn't work with images (iframe solution).

I've looked to Google's Picasa or Google+ and it would be perfect to have their multidownload solution: they build their zip "on-demand" which means the browser keeps downloading a file, not knowing its final size, but once it achieved 100%, it stops and everything worked smoothly.

I don't do any idea of how to do this. Any ideas?

Tks!

Based on Alexei Levenkov and OP's comments, I've learned that it is possible to begin writing a zip file to a stream without having to completely assemble it before hand. Fortunately, .NET 4.5 provides a built in utility class for exactly this purpose: System.IO.Compression.ZipArchive .

Unfortunately, as described in this question , this class has a few incompatibilities with the HttpResponse.OutputStream which we intend to write to, since HttpResponse.OutputStream is not seekable, whereas ZipArchive requires any stream it writes to implement the Position member for a seekable stream.

There is hope however: svick has posted an answer that diagnoses the issue and provides a way to work around it. The workaround involves simply creating a "go-between" stream, which implements the members ZipArchive requires, and simply forwards whatever is written to it into another stream (ie Response.OutputStream ).


If you want to create the zip file server side, which I think is easier, you might want to look at the System.IO.Compression.ZipFile class, which provides static methods for creating archives from existing files.

Eg. creating an archive from a directory on the server:

// In ASP.NET, getting the UNC path to the directory which will be zipped
string dirpath = Server.MapPath('~/app/foldertodownload');

// Destination path
string destpath = Server.MapPath('~/public/downloads.zip');

ZipFile.CreateFromDirectory(dirpath, destpath);

Now all you need to do is write this zip file to the response with the appropriate headers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM