Re: Creating a zip file(s) for download.
Re: Creating a zip file(s) for download.
- Subject: Re: Creating a zip file(s) for download.
- From: Timo Hoepfner <email@hidden>
- Date: Wed, 27 Dec 2006 11:27:15 +0100
Am 26.12.2006 um 19:10 schrieb James Cicenia:
I need to create a file(s) in memory on the fly and then download
it to the user as a zip file.
Anyone have a simple example or process?
Hi James,
here's some code I'm using. It both adds files from the file system
and generated text into the archive.
You could then use a FileInputStream to construct a NSData and return
that to the client.
Or you use PipedInput/OutputStreams to "convert" the ZipOutputStream
into an InputStream and directly feed it into an NSData.
Sample code for download also below.
HTH,
Timo
File dir = new File("/path/to/target/directory");
dir.mkdirs();
// absolute paths to the files you want to zip
String[] filenames = ...;
byte[] buf = new byte[1024];
File outFile = new File(dir, "yourOutputFile.zip");
try {
// Create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream
(outFile));
// 1. add files from file system
for (int i = 0; i < filenames.length; i++) {
FileInputStream in = new FileInputStream(filenames[i]);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(new File(filenames[i]).getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// 2. add some html/text as file to the archive
String html = ...;
if (html != null) {
out.putNextEntry(new ZipEntry("yourFileName.html"));
out.write(html.getBytes("UTF-8"));
out.closeEntry();
}
// Complete the ZIP file
out.close();
} catch (Exception e) {
outFile.delete();
throw e;
}
public class DownloadComponent extends WOComponent {
public NSData data;
public String fileName;
public String contentType;
public DownloadComponent(WOContext context) {
super(context);
}
public void appendToResponse(WOResponse aResponse, WOContext
aContext) {
super.appendToResponse(aResponse, aContext);
if (data != null) {
aResponse.disableClientCaching();
aResponse.removeHeadersForKey("Cache-Control");
aResponse.removeHeadersForKey("pragma");
if (contentType == null) {
aResponse.setHeader("application/octet-stream",
"content-type");
} else {
aResponse.setHeader(contentType, "content-type");
}
if (fileName != null) {
aResponse.setHeader("attachment; filename=\"" +
fileName + "\"",
"content-disposition");
} else {
aResponse.setHeader("attachment", "content-
disposition");
}
aResponse.setHeader(Integer.toString(data.length()),
"content-length");
aResponse.setContent(data);
}
}
}
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Webobjects-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden