---
title: "ASP.NET上传文件方法"
author: "wjxa"
date: "2010-03-08T23:12:59Z"
tags: [".net", "ASP", "ASP.net", "C", "C++"]
categories: ["编程语言"]
slug: "asp-net"
draft: false
lastmod: "2010-03-08T23:12:59Z"
id: 610806
url: "https://wjxa.iteye.com/blog/610806"
---

\[code="c#"] 1.#region 上传文件的方法 2. /// 3. /// 上传文件方法 4. /// 5. /// 上传控件ID 6. /// 允许上传的扩展文件名类型,如：string\[] allowExtensions = { ".doc", ".xls", ".ppt", ".jpg", ".gif" }; 7. /// 允许上传的最大大小，以M为单位 8. /// 保存文件的目录，注意是绝对路径,如：Server.MapPath("~/upload/"); 9. /// 保存的文件名，如果是""则以原文件名保存 10. private void Upload(FileUpload myFileUpload, string\[] allowExtensions, int maxLength, string savePath, string saveName) 11. { 12. // 文件格式是否允许上传 13. bool fileAllow = false; 14. 15. //检查是否有文件案 16. if (myFileUpload.HasFile) 17. { 18. // 检查文件大小, ContentLength获取的是字节，转成M的时候要除以2次1024 19. if (myFileUpload.PostedFile.ContentLength / 1024 / 1024 &gt;= maxLength) 20. { 21. throw new Exception("只能上传小于2M的文件！"); 22. } 23. 24. //取得上传文件之扩展文件名，并转换成小写字母 25. string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower(); 26. string tmp = ""; // 存储允许上传的文件后缀名 27. //检查扩展文件名是否符合限定类型 28. for (int i = 0; i &lt; allowExtensions.Length; i++) 29. { 30. tmp += i == allowExtensions.Length - 1 ? allowExtensions\[i] : allowExtensions\[i] + ","; 31. if (fileExtension == allowExtensions\[i]) 32. { 33. fileAllow = true; 34. } 35. } 36. 37. if (fileAllow) 38. { 39. try 40. { 41. string path = savePath + (saveName == "" ? myFileUpload.FileName : saveName); 42. //存储文件到文件夹 43. myFileUpload.SaveAs(path); 44. } 45. catch (Exception ex) 46. { 47. throw new Exception(ex.Message); 48. } 49. } 50. else 51. { 52. throw new Exception("文件格式不符，可以上传的文件格式为：" + tmp); 53. } 54. } 55. else 56. { 57. throw new Exception("请选择要上传的文件！"); 58. } 59. } 60. #endregion \[/code]