1.html代碼:

<asp:FileUpload runat="server" ID="UpLoadFile"/> <asp:Button runat="server" ID="btnUpLoad" OnClick="btnUpLoad_Click" Text="上傳"/>
2.后台代碼:

public partial class UpLoadFilesByStream : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// 上傳 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnUpLoad_Click(object sender, EventArgs e) { //對於文件的格式和大小的判斷,在上一篇已經涉及,這里省略。 if (this.UpLoadFile.HasFile) { //HttpPostedFile類提供對客戶端已上載的單獨文件的訪問 HttpPostedFile hpf = this.UpLoadFile.PostedFile; //HttpPostedFile hpf = Request.Files[0]; //文件名 string fileName = Path.GetFileName(hpf.FileName); //文件大小,單位字節 int fileContentLength = hpf.ContentLength; //上傳路徑 string filePath = Server.MapPath("/Files/"); //二進制數組 byte[] fileBytes = null; fileBytes = new byte[fileContentLength]; //創建Stream對象,並指向上傳文件 Stream fileStream = hpf.InputStream; //從當前流中讀取字節,讀入字節數組中 fileStream.Read(fileBytes, 0, fileContentLength); //全路徑(路勁+文件名) string fullPath = filePath + fileName; //保存到磁盤 SaveToDisk(fileBytes, fullPath); } } /// <summary> /// 保存到磁盤 /// </summary> /// <param name="bytes">字節數組</param> /// <param name="saveFullPath">全路徑</param> /// <returns></returns> public void SaveToDisk(byte[] bytes, string saveFullPath) { var fullPath = Path.GetDirectoryName(saveFullPath); //如果沒有此文件夾,則新建 if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } //創建文件,返回一個 FileStream,它提供對 path 中指定的文件的讀/寫訪問。 using (FileStream stream = File.Create(saveFullPath)) { //將字節數組寫入流 stream.Write(bytes, 0, bytes.Length); stream.Close(); } } }
測試通過!