標籤:多個 exception 命名 controls protected 檔案格式 last log onclick
前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Alum.aspx.cs" Inherits="Album_Default" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="fup" runat="server" /> <br /> <br /> <asp:Button ID="btnUp" Text="上傳圖片" runat="server" OnClick="btnUp_Click" /> <asp:Label id="lblInfo" runat="server" ForeColor="Red" Font-Size="13px" ></asp:Label> <br /> <br /> <asp:LinkButton ID="lbnPhoto" runat="server" PostBackUrl="~/Album/Photo.aspx" Text="查看照片"></asp:LinkButton> </div> </form></body></html>
後台:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Album_Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { } private static bool IsAllowedExtension(FileUpload upfile) { string strOldFilePath = ""; string strExtension = ""; string[] arrExtension = { ".gif", ".jpg", ".bmp", ".png" }; if (upfile.PostedFile.FileName != string.Empty) { strOldFilePath = upfile.PostedFile.FileName;//獲得檔案的完整路徑名 strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));//獲得檔案的副檔名,如:.jpg for (int i = 0; i < arrExtension.Length; i++) { if (strExtension.Equals(arrExtension[i])) { return true; } } } return false; } //圖片上傳並將圖片重新命名 protected void btnUp_Click(object sender, EventArgs e) { myClass myclass = new myClass(); try { if (fup.PostedFile.FileName == "") { lblInfo.Text = "請選擇檔案!"; } else { //string filepath = fup.PostedFile.FileName; if (!IsAllowedExtension(fup)) { lblInfo.Text = "上傳檔案格式不正確!"; } if (IsAllowedExtension(fup) == true) { string filepath = fup.PostedFile.FileName; string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); string serverpath = Server.MapPath("picture/") + filename; fup.PostedFile.SaveAs(serverpath); serverpath = "picture/" + filename; DateTime now = DateTime.Now; string sql = "insert into Photo (photoname,uptime,path)values(‘" + filename + "‘,‘" + now + "‘,‘" + serverpath + "‘)"; int flag = myclass.DataSQL(sql); if (flag == 1) lblInfo.Text = "上傳成功!"; else lblInfo.Text = "上傳失敗!"; } else { lblInfo.Text = "請上傳圖片!"; } } } catch (Exception ex) { lblInfo.Text = "上傳發生錯誤!原因是:" + ex.ToString(); } }}
可以上傳圖片。限制圖片類型。還缺少同時上傳多個檔案和限制圖片大小。最後補充一下看了很久的注釋_(:з」∠)_。發一下馬克一下。說不定魔改完就不見了。。
=L=圖片上傳整理