Copy codeThe Code is as follows:
[HttpPost]
Public string UploadImage ()
{
// String ss = Request. Form ["uploadFile"];
// Return ss;
HttpPostedFileBase uploadFile = Request. Files [0];
String fileName = uploadFile. FileName;
Int fileSize = uploadFile. ContentLength;
String fileExt = Path. GetExtension (fileName). ToLower ();
String message = "";
If (! (FileExt = ". png" | fileExt = ". gif" | fileExt = ". jpg" | fileExt = ". jpeg "))
{
Message = "the image type can only be gif, png, jpg, or jpeg ";
Return message;
}
Else
{
If (fileSize> (int) (500*1024 ))
{
Message = "the image size cannot exceed 500KB ";
Return message;
}
Else
{
Random r = new Random ();
String uploadFileName = DateTime. Now. ToString ("yyyyMMddhhmmss") + r. Next (100000,999 999) + fileExt;
Try
{
String directoryPath = Server. MapPath ("~ /UploadImages /");
If (! Directory. Exists (directoryPath) // This folder is created if it does not exist.
{
Directory. CreateDirectory (Server. MapPath ("~ /UploadImages /"));
}
UploadFile. SaveAs (Server. MapPath ("~ /UploadImages/") + uploadFileName );
Message = uploadFileName;
Return message;
}
Catch (Exception ex)
{
Message = ex. Message;
Return message;
}
}
}
}