CodeToday: Upload Image and Resize
using System.IO;
using System.Web;
public static string UploadImage(string newFileName, string directory, FileUpload fileUpload, int imageSize, bool overwrite)
{
if (fileUpload.HasFile)
{
string oldFileName = fileUpload.FileName;
DirectoryInfo dirTempInfo = new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath + "Temp");
if (!dirTempInfo.Exists) dirTempInfo.Create();
string tempPath = dirTempInfo.FullName + @"\" + oldFileName;
fileUpload.SaveAs(tempPath);
FileInfo tempInfo = new FileInfo(tempPath);
string extension = tempInfo.Extension;
if (newFileName == "") newFileName = tempInfo.Name.Substring(0, tempInfo.Name.IndexOf(extension));
string newFullName = newFileName + extension;
DirectoryInfo dirInfo = new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath + directory);
if (!dirInfo.Exists) dirInfo.Create();
string filePath = dirInfo.FullName + @"\" + newFullName;
FileInfo fileInfo = new FileInfo(filePath);
if (!fileInfo.Exists || overwrite)
{
if (fileInfo.Exists) fileInfo.Delete();
if (imageSize > 0)
{
ResizeImage(tempPath, filePath, imageSize);
tempInfo.Delete();
}
else tempInfo.MoveTo(filePath);
}
else tempInfo.Delete();
return directory + "/" + newFullName;
}
else return "";
}
กำหนดขนาดไฟล์สูงสุดที่ upload หน่วยเป็น KB ได้ที่ web.config
<system.web>
<httpRuntime maxRequestLength="4096"/>
</system.web>
ResizeImage ได้มาจาก CodeToday: ResizeImage
Imagination is more Important than Knowledge... /A.Einstein