10 April 2017

Uploading An Image File with Unique Filename and Save It In A Folder


I just have a requirement to upload an image file in a folder named "UploadedFiles" and replace its file extension from ".whateverFileExtension" to ".jpg".
And to ensure that each picture will have a unique (or at least have a higher probability of a unique filename), I will use SyncLock method and Random class to generate random number (ex. from 1 to 10,000,000) and assign the auto-generated number to every uploaded picture.

Below is my sample code:

<HTML>

<input type="file" id="fileUpload" runat="server" />
<input type="submit" id="btnUploadFile" runat="server" value="Upload" onserverclick="btnUploadFile_OnServerClick" />


<CODE BEHIND>

private string _myRandomNumber;
private static readonly Random Random = new Random();
private static readonly object SyncLock = new object();

public static int RandomNumber(int min, int max)
{
    lock (SyncLock)
    {
        return Random.Next(min, max);
    }
}

protected void btnUploadFile_OnServerClick(object sender, EventArgs e)
{
    _myRandomNumber = RandomNumber(0, 10000000).ToString("D");
    int newPictureId = Int32.Parse(_myRandomNumber);
    string baseDirectory = Server.MapPath("~/UploadedFiles/");
    fileUpload.PostedFile.SaveAs((baseDirectory + (newPictureId + ".jpg")));
}

No comments:

Post a Comment