標籤:
using System;using System.Collections.Generic;using System.Text;using System.Web.UI.WebControls;using System.IO;namespace AIMSCommon{ /// <summary> /// 檔案上傳協助類 /// </summary> public class UploadHelper { /// <summary> /// 檔案上傳 /// </summary> /// <param name="path">儲存路徑</param> /// <param name="filleupload">上傳檔案控制項</param> /// <returns></returns> public static string FileUpload(string path, FileUpload filleupload) { try { bool fileOk = false; //取得檔案的副檔名,並轉換成小寫 string fileExtension = System.IO.Path.GetExtension(filleupload.FileName).ToLower(); //檔案格式 string[] allowExtension = { ".rar", ".zip", ".rar", ".ios", ".jpg", ".png", "bmp", ".gif", ".txt" }; if (filleupload.HasFile) { //對上傳的檔案的類型進行一個個匹對 for (int i = 0; i < allowExtension.Length; i++) { if (fileExtension == allowExtension[i]) { fileOk = true; break; } } } //如果符合條件,則上傳 if (fileOk) { if (Directory.Exists(path) == false)//如果不存在就建立file檔案夾 { Directory.CreateDirectory(path); } if (!FileHelper.IsExistFile(path + filleupload.FileName)) { int Size = filleupload.PostedFile.ContentLength / 1024 / 1024; if (Size > 10) { return "上傳失敗,檔案過大"; } else { filleupload.PostedFile.SaveAs(path + filleupload.FileName); return "上傳成功"; } } else { return "上傳失敗,檔案已存在"; } } else { return "不支援【" + fileExtension + "】檔案格式"; } } catch (Exception) { return "上傳失敗"; } } }}
檔案上傳協助類