Custom UploadStreamProvider Sample
To see this sample in action, download the SlickUpload package and configure it for your environment.
NOTE: the maximum allowed request size for this sample is 1000 MB. If you attempt to upload files larger than this,
you will recieve a oversized upload error which SlickUpload will handle gracefully. This is controlled by the maxRequestLength attribute of the
httpRuntime key in the web.config file.
Description
Not only can you use the built in File and SqlClient UploadStreamProviders, you can also create your own custom provider that returns a stream for SlickUpload to write files to. This
allows you to do any stream transformations on the file – checksum, encrypt, etc.
This sample demonstrates an UploadStreamProvider that zips all files as they are uploaded. The configuration is as follows:
<uploadStreamProvider provider="Custom" location="~/CustomUploadStreamProvider/Files/" type="ZipUploadStreamProviderCS, App_SubCode_CSCode" />
The heart of the UploadStreamProvider is the GetOutputStream method. SlickUpload calls this method for each file that is uploaded to get a stream to which to write the file. In this case,
we create and return a zip stream:
public Stream GetOutputStream(UploadedFile file)
{
FileStream fileS = null;
ZipOutputStream zipS = null;
try
{
string outputPath = GetZipPath(file);
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
fileS = File.OpenWrite(outputPath);
zipS = new ZipOutputStream(fileS);
zipS.SetLevel(5);
zipS.PutNextEntry(new ZipEntry(file.ClientName));
file.LocationInfo[FileNameKey] = outputPath;
return zipS;
}
catch
{
if (fileS != null)
fileS.Dispose();
if (zipS != null)
zipS.Dispose();
return null;
}
}
The GetInputStream is a mirror image of this method – it returns a stream with the contents of the file. This isn't required to be implemented
if your code accesses the file data some other way, so you may throw a NotImplementedException from this method.
The RemoveOutput is the last method in the UploadStreamProvider and should remove anything created by the stream returned from the GetOutputStream
method. It will be called if the upload fails or errors and needs to be cleaned up.
|