Monday, August 15, 2005

Saving Images with some checks

// Initialize variables
string sSavePath;
string sSrvPath = null;

// Set constant values
sSrvPath = Server.MapPath("propertypics/");


// If file field isn’t empty
if (filUpload.PostedFile != null)
{
// Check file size (mustn’t be 0)
HttpPostedFile myFile = filUpload.PostedFile;
int nFileLen = myFile.ContentLength;

if (nFileLen == 0)
{
lblOutput.Text = "There wasn't any file uploaded.";
return;
}

// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData,0,nFileLen);

// Make sure a duplicate file doesn’t exist. If it does, keep on appending an incremental numeric until it is unique

string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;

while (System.IO.File.Exists(sSrvPath + sFilename ))
{
file_append++;

sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + ".jpg";
}

// Save the stream to disk
System.IO.FileStream newFile = new System.IO.FileStream(sSrvPath + sFilename, System.IO.FileMode.Create);
newFile.Write(myData,0, myData.Length);
newFile.Close();
}

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?