自我感觉封装得还不错!!!
代码如下:
C#代码
class="star" src="/Upload/Images/2014073121/40B102E0EF997EA6.png" alt="收藏代码" />
- #region 上传文件的方法
-
-
-
-
-
-
-
-
- private void Upload(FileUpload myFileUpload, string[] allowExtensions, int maxLength, string savePath, string saveName)
- {
-
- bool fileAllow = false;
-
-
- if (myFileUpload.HasFile)
- {
-
- if (myFileUpload.PostedFile.ContentLength / 1024 / 1024 >= maxLength)
- {
- throw new Exception("只能上传小于2M的文件!");
- }
-
-
- string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower();
- string tmp = "";
-
- for (int i = 0; i < allowExtensions.Length; i++)
- {
- tmp += i == allowExtensions.Length - 1 ? allowExtensions[i] : allowExtensions[i] + ",";
- if (fileExtension == allowExtensions[i])
- {
- fileAllow = true;
- }
- }
-
- if (fileAllow)
- {
- try
- {
- string path = savePath + (saveName == "" ? myFileUpload.FileName : saveName);
-
- myFileUpload.SaveAs(path);
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- }
- else
- {
- throw new Exception("文件格式不符,可以上传的文件格式为:" + tmp);
- }
- }
- else
- {
- throw new Exception("请选择要上传的文件!");
- }
- }
- #endregion
以下是测试的代码:
C#代码
- try
- {
- string[] ss = { ".jpg", ".gif" };
- string path = Request.MapPath("~/upload/");
- Upload(FileUpload1, ss, 1, path, "");
- Label1.Text = "文件上传成功!";
- }
- catch (Exception ex)
- {
- Label1.Text = ex.Message;
- }
以前一直没有认真的学习异常处理,今天弄了一下还发现异常处理还蛮好的。。。起码代码量上感觉比if..else..少。。。呵呵。。。