CodeToday: Upload File
using System.IO;
public static string UploadFile(string newFileName, string directory, FileUpload fileUpload, bool overwrite)
{
if (fileUpload.PostedFile.FileName != "")
{
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();
tempInfo.MoveTo(filePath);
}
else tempInfo.Delete();
return dirInfo.FullName + "/" + newFullName;
}
return "";
}
กำหนดขนาดไฟล์สูงสุดที่ upload หน่วยเป็น KB ได้ที่ web.config
<system.web>
<httpRuntime maxRequestLength="4096"/>
</system.web>
Imagination is more Important than Knowledge... /A.Einstein