วันพุธที่ 16 พฤษภาคม พ.ศ. 2555

Upload Image and Resize


1.  using System.IO;
2.  using System.Web;

3.  public static string UploadImage(string newFileName, string directory, FileUpload fileUpload, int imageSize, bool overwrite)
4.  {
5.  if (fileUpload.HasFile)
6.  {
7.  string oldFileName = fileUpload.FileName;
8.  DirectoryInfo dirTempInfo = new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath + "Temp");
9.  if (!dirTempInfo.Exists) dirTempInfo.Create();
10. string tempPath = dirTempInfo.FullName + @"\" + oldFileName;
11. fileUpload.SaveAs(tempPath);
12. FileInfo tempInfo = new FileInfo(tempPath);
13. string extension = tempInfo.Extension;
14. if (newFileName == "") newFileName = tempInfo.Name.Substring(0, tempInfo.Name.IndexOf(extension));
15. string newFullName = newFileName + extension;
16. DirectoryInfo dirInfo = new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath + directory);
17. if (!dirInfo.Exists) dirInfo.Create();
18. string filePath = dirInfo.FullName + @"\" + newFullName;
19. FileInfo fileInfo = new FileInfo(filePath);
20. if (!fileInfo.Exists || overwrite)
21. {
22. if (fileInfo.Exists) fileInfo.Delete();
23. if (imageSize > 0)
24. {
25. ResizeImage(tempPath, filePath, imageSize);
26. tempInfo.Delete();
27. }
28. else tempInfo.MoveTo(filePath);
29. }
30. else tempInfo.Delete();
31. return directory + "/" + newFullName;
32. }
33. else return "";
34. }

35.  เราต้องกำหนดขนาดไฟล์สูงสุดที่ upload หน่วยเป็น KB ได้ที่ web.config แต่เท่าที่ทำแม้กำหนดไฟล์ใหย๋มากๆ ก็ส่งไฟล์ขนาดมากๆขึ้นไปไม่ได้อยู่ดีเพราะ Timeout return error

36. <system.web>
<httpRuntime maxRequestLength="4096"/>
< /system.web>

ไม่มีความคิดเห็น:

แสดงความคิดเห็น