Hi, my name is Harold Javier. I am an ASP.NET (dotNet) trainer, coach, mentor, and consultant for more than 8 years. It is my mission to teach, educate, and train people about some simple solutions to common problems we experience either as a software developer or as a researcher on topics about ASP.NET Core, ASP.NET MVC, ASP.NET Web API, ASP.NET Web Form, and .NET (dotNet) technology in general.
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")));
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment