In recent project I had to make two different types of FileUploads work -
1. Asp.net fileupload a
2. Ajax - AsyncFileupload
Both implementations were not that hard. Complete description is as follows:
Asp.net FileUpload
Visible="false" />
ValidationExpression="^(([a-zA-Z]:)|(\\{1}\w+)\$?)(\\(\w.*))+(.xls|.xlsx)$" ControlToValidate="fuPricingAttachment">
In above example -
is the control used and the regex is for informing that only .xls and .xlsx types of files can be uploaded. ValidationGroup allows to validate the content when 'submit' button is clicked.
I did create -
public string pricingFileGuid
{
get
{
if (ViewState["strPricingFileGuid"] != null)
return ViewState["strPricingFileGuid"].ToString();
else
return string.Empty;
}
set { ViewState["strPricingFileGuid"] = value; }
}
so that I can cache the file content with key of GUID.
Core piece of storing file content is - this way content does not get stored until user decides to save the file content in the database by hitting 'Save' or 'Submit'
var fileKey = Guid.NewGuid();
if (!string.IsNullOrEmpty(fileName))
{
var fileStream = new Byte[fuPricingAttachment.PostedFile.ContentLength];
fuPricingAttachment.PostedFile.InputStream.Read(fileStream, 0, fuPricingAttachment.PostedFile.ContentLength);
Cache[fileKey.ToString()] = fileStream;
this.pricingFileGuid = fileKey.ToString();
}
The code which Saves file to file share and to database :
if (!string.IsNullOrEmpty(this.generalFileGuid))
{
var fileStream = new Byte[((Byte[])Cache[this.generalFileGuid]).Length];
try
{
// Open file for reading
System.IO.FileStream _FileStream = new System.IO.FileStream(lnkGeneralAttachment.Text, System.IO.FileMode.Create, System.IO.FileAccess.Write);
// Writes a block of bytes to this stream using data from a byte array.
_FileStream.Write(fileStream, 0, fileStream.Length);
// close file stream
_FileStream.Close();
}
catch (Exception _Exception)
{
throw new Exception("Error while uploading file.");
}
}
At any point if you have any questions/comments or you want full code of pages let me know and I might be able to provide it to you within no time.
I will upload AsyncFileUpload code tomorrow :) happy coding!