標籤:style blog http color os io 檔案 for
Asp.Net中很方便就能做個上傳,例如做一個圖片的上傳:
<asp:FileUpload ID="picUpload" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="上傳" CssClass="btn" onclick="btnUpload_Click" CausesValidation="false"/>
對應的上傳代碼如下:
protected void btnUpload_Click(object sender, EventArgs e) { if (!picUpload.HasFile) { picAssetItem.ImageUrl = ""; labUpload.Text = "請選擇要上傳的圖片"; return; } string fileExtension = Path.GetExtension(picUpload.FileName).ToLower(); Match match = Regex.Match(fileExtension, "jpg|jpeg|png"); if (!match.Success) { picAssetItem.ImageUrl = ""; labUpload.Text = "請上傳jpg或者png格式的圖片"; return; } if (picUpload.PostedFile.ContentLength > 8192000) { picAssetItem.ImageUrl = ""; labUpload.Text = "檔案大小超出8M!請重新選擇!"; return; } string uploadPath = ConfigurationManager.AppSettings["UploadPath"]; uploadPath += DateTime.Today.ToString("yyyy-MM-dd"); if (!Directory.Exists(Server.MapPath(uploadPath))) { log.Info("Creating folder " + uploadPath + " on server"); try { Directory.CreateDirectory(Server.MapPath(uploadPath)); } catch (Exception ex) { log.Error("Failed to create folder"); log.Error(ex); labUpload.Text = "系統錯誤,上傳失敗"; return; } } string imageUUID = System.Guid.NewGuid().ToString(); string imageName = imageUUID + fileExtension; string imagePath = Server.MapPath(uploadPath + "/" + imageName); string thumbImagePath = Server.MapPath(uploadPath + "/thumb-" + imageName); try { picUpload.PostedFile.SaveAs(imagePath); System.Drawing.Image image = System.Drawing.Image.FromStream(picUpload.PostedFile.InputStream, true); System.Drawing.Size newSize = new System.Drawing.Size(400, 300); System.Drawing.Image bitmap = new System.Drawing.Bitmap(newSize.Width, newSize.Height); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap); graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.Clear(System.Drawing.Color.White); graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.GraphicsUnit.Pixel); bitmap.Save(thumbImagePath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { log.Error("Failed to save image"); log.Error(ex); labUpload.Text = "系統錯誤,上傳失敗"; return; } txtImagePath.Text = DateTime.Today.ToString("yyyy-MM-dd") +"/" + imageName; picAssetItem.ImageUrl = uploadPath + "/thumb-" + imageUUID + ".jpg"; labUpload.Text = "上傳成功"; }
上面的代碼是把圖片存到本地的檔案夾中,按日期進行儲存,儲存的檔案用uuid進行命名。同時產生一張固定大小的縮圖,用來顯示用。
上傳小檔案,還是蠻方便的,不過需要注意的是,對伺服器的檔案夾,必須對NETWORK組添加讀寫的許可權:
另外,貌似只能上傳小於4M 的檔案,稍大的檔案上傳會直接無法顯示網頁。這個也是可以設定的,具體不想深究,能用就行:
<system.web>...<!-- 加入下面設定--><httpRuntime executionTimeout="90" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100"/></system.web>