2012年12月24日 星期一
主子資料表的新增
'新增資料到訂貨主檔
'儲存資料後,超連結到顯示訂單的網頁
Dim connstr As String = "Data Source=120.xxx.xx.xxx;UID=xx;PWD=xx;Database=北風貿易"
Dim sqlconn As SqlConnection = New SqlConnection(connstr)
Dim sqlcmdstr As String = "insert into 訂貨主檔(客戶編號, 員工編號, 訂單日期, 要貨日期, 送貨方式) values(@客戶編號, @員工編號, @訂單日期, @要貨日期, @送貨方式);select @@IDENTITY"
Dim sqlcmd As New SqlCommand(sqlcmdstr, sqlconn)
sqlcmd.Parameters.AddWithValue("@客戶編號", Me.TextBox1.Text)
sqlcmd.Parameters.AddWithValue("@員工編號", Me.TextBox6.Text)
sqlcmd.Parameters.AddWithValue("@訂單日期", Me.TextBox2.Text)
sqlcmd.Parameters.AddWithValue("@要貨日期", Me.TextBox4.Text)
sqlcmd.Parameters.AddWithValue("@送貨方式", Me.TextBox5.Text)
'sqlcmd.Parameters.AddWithValue("@newid", Me.TextBox7.Text)
'sqlcmd.Parameters.AddWithValue("@訂單日期", Me.TextBox2.Text)
sqlconn.Open()
Dim result As SqlDataReader
result = sqlcmd.ExecuteReader
If result.HasRows Then
Do While result.Read()
'Response.Write(result(0).ToString)
Me.Label1.Text = result(0).ToString
Me.TextBox3.Text = result(0).ToString
Loop
Else
Response.Write("No rows returned.")
End If
result.Close()
'result.Read()
sqlconn.Close()
'Response.Write(result.ToString)
'Response.Redirect("gridview.aspx")
Me.GridView1.DataBind()
Protected Sub FormView1_ItemInserted(sender As Object, e As System.Web.UI.WebControls.FormViewInsertedEventArgs) Handles FormView1.ItemInserted
'當子資料表有新項目新增時, 更新下方的訂單明細gridview1
Me.GridView1.DataBind()
End Sub
Protected Sub FormView1_PreRender(sender As Object, e As EventArgs) Handles FormView1.PreRender
'當formview重新整理時,將訂單號碼填進去
Dim orderid As TextBox = CType(Me.FormView1.FindControl("訂單號碼TextBox"), TextBox)
orderid.Text = Me.TextBox3.Text
End Sub
Private Sub Calendar2_DayRender(sender As Object, e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar2.DayRender
'限制只能在7天以後開放選取交期
e.Day.IsSelectable = e.Day.Date > Now.AddDays(7).ToShortDateString
End Sub
Protected Sub Calendar2_SelectionChanged(sender As Object, e As EventArgs) Handles Calendar2.SelectionChanged
'輸入交期
Me.TextBox4.Text = Me.Calendar2.SelectedDate
End Sub
'更新產品編號
Protected Sub DropDownList4_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim productid As TextBox = CType(Me.FormView1.FindControl("產品編號TextBox"), TextBox)
Dim drop_product As DropDownList = CType(Me.FormView1.FindControl("DropDownList4"), DropDownList)
productid.Text = drop_product.SelectedValue.ToString
'Dim ds As DataSet = SqlDataSource1.Select
Dim connstr As String = "Data Source=xxx.xx.xx.xx;UID=xx;PWD=xx;Database=北風貿易"
Dim sqlconn As SqlConnection = New SqlConnection(connstr)
Dim cmd As New SqlCommand("select 單價 from 產品資料 where 產品編號 = @prodid", sqlconn)
cmd.Parameters.AddWithValue("@prodid", Int(drop_product.SelectedValue))
Dim reader As SqlDataReader
sqlconn.Open()
reader = cmd.ExecuteReader
If reader.Read Then
Dim price_text As TextBox = CType(Me.FormView1.FindControl("單價TextBox"), TextBox)
price_text.Text = reader(0).ToString
End If
sqlconn.Close()
End Sub
If Me.TextBox3.Text <> "" Then
Dim connstr As String = "Data Source=xxx.xxx.xx.xx;UID=xx;PWD=xx;Database=北風貿易"
Dim sqlconn As SqlConnection = New SqlConnection(connstr)
Dim cmd As SqlCommand
cmd = New SqlCommand("delete 訂貨主檔 where 訂單號碼='" & Me.TextBox3.Text & "'", sqlconn)
Dim result As Integer
sqlconn.Open()
result = cmd.ExecuteNonQuery
Response.Write(result)
sqlconn.Close()
'If result = -1 Then
Me.TextBox3.Text = ""
Dim orderid As TextBox = CType(Me.FormView1.FindControl("訂單號碼TextBox"), TextBox)
orderid.Text = ""
Me.TextBox4.Text = ""
'End If
End If
2012年12月18日 星期二
在visual studio 2010 aspx網頁webform複製改名(重新命名)後產生的錯誤
上網找了一陣子,終於找到當aspx網頁檔名被修改後發生錯誤的解法,參考自
為了避免此網頁以後找不到,因此把重點摘錄如下
2012年12月8日 星期六
網頁產生一二維條碼
因為教學需要,所以放上網路上找到的一二維條碼產生DLL
一維條碼 128碼 DLL(方法1),先下載以下DLL,並加入參考
https://docs.google.com/open?id=0Bxaw7Z2hq9CFWG1iRzJacFN1aGM
以下所產生的一維條碼會顯示在另一個瀏覽器,並不方便
'一維條碼 128碼 呼叫程式碼
Dim b As BarcodeLib.Barcode = New BarcodeLib.Barcode()
'支援39, 128, EAN, UPC等
Dim type As BarcodeLib.TYPE = BarcodeLib.TYPE.CODE128
Try
'Me.Image1.Image = b.Encode(type, TextBox1.Text.Trim)
Dim data As String = Me.TextBox1.Text
Dim image As New System.Drawing.Bitmap(200, 200)
image = b.Encode(type, TextBox1.Text.Trim)
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif)
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
一維條碼 128碼 DLL(方法2),也是下載DLL,並加入參考
將編碼的圖片寫在另外一個.ashx 泛型處理常式中
Imports System.Web
Imports System.Web.Services
Imports System.Web.SessionState ' 要使用 Session 必需加入此命名空間
Imports System.IO
Imports System.Drawing.Imaging
Public Class barcode
Implements System.Web.IHttpHandler, IRequiresSessionState
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim encodestr As String = ""
'context.Request("encodestr") 是從傳過來的網址中抓取問號後面encoderstr的變數值
'例如 http://barcode.ashx?encodestr="123" 則會抓取123
If context.Session("encodestr") IsNot Nothing Then
'利用TryParse函數判斷使用者輸入的是數字或是文字
'If Integer.TryParse(context.Request("scid").Trim(), encoderstr) Then
'End If
encodestr = context.Session("encodestr").ToString
Dim b As BarcodeLib.Barcode = New BarcodeLib.Barcode()
Try
Dim image As New System.Drawing.Bitmap(200, 200)
'支援39, 128, EAN, UPC等,目前是將encodestr編成128碼
Dim type As BarcodeLib.TYPE = BarcodeLib.TYPE.CODE128
image = b.Encode(type, encodestr.ToString)
context.Response.ContentType = "Image/Gif"
context.Response.Clear()
image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif)
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
Else
context.Response.Write("sessioin error")
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
二維條碼 qr code DLL
https://docs.google.com/open?id=0Bxaw7Z2hq9CFa0t4dkVkMEZCOFU
'二維條碼 呼叫程式碼
Dim encoder As New ByCase.Lib.QRCode.Codec.QRCodeEncoder
'編碼有3種,分別是byte, alphanumeric, numeric
encoder.QRCodeEncodeMode = ByCase.Lib.QRCode.Codec.QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC
'(image pixels per QRCode pixel): 1, 2, 3, 4, 5, 10, 15, 30. ( in pixels )
encoder.QRCodeScale = 5
'二维码所能包含的字符信息量是由QrcodeVersion的设置值来决定的。将QrcodeVersion设置到20的时候,就已经可以容乃到300多个字节
encoder.QRCodeVersion = 20
'ByCase.Lib.QRCode.Codec.QRCodeEncoder.ERROR_CORRECTION.H L M Q
encoder.QRCodeErrorCorrect = ByCase.Lib.QRCode.Codec.QRCodeEncoder.ERROR_CORRECTION.H
'只能大寫英文, 數字, 空格+-*/冒號,不可以小寫、不可底線不可特殊符號
Dim data As String = Me.TextBox1.Text.ToUpper
Dim image As New System.Drawing.Bitmap(200, 200)
image = encoder.Encode(data)
Image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif)
二維條碼(方法2)
Google charts提供非常方便的API,可以產生QR Code圖片。
http://code.google.com/apis/chart/docs/gallery/qr_codes.html(API說明)
以下面URL為例,紅色部份為關鍵參數
https://chart.googleapis.com/chart?chs=120x120&cht=qr&chl=陳錫川&choe=UTF-8&chld=M|2
其中:
chs: QR code 圖片大小
cht: 圖片類型,google charts用這個參數產生各種圖片,這裡當然就填qr
chl: 要藏在QR code裡的文字,必須編成punycode(urlencode)。
choe: 編碼。請注意只支援iso-8859-1, sjis, utf8。詳見API說明網頁。
chld: 其他參數。M是錯誤修正層次,有L, M, Q, H等四級;後面的數字是QR code周圍白邊的寬度。
在webform放置textbox1與button,接著在button中撰寫以下程式即可
Dim imgsrc As String = "http://chart.apis.google.com/chart?chs=" & "400x400" & "&chl=" & Me.TextBox1.Text & "&choe=UTF-8&cht=qr"
Image1.ImageUrl = imgsrc
一維條碼 128碼 DLL(方法1),先下載以下DLL,並加入參考
https://docs.google.com/open?id=0Bxaw7Z2hq9CFWG1iRzJacFN1aGM
以下所產生的一維條碼會顯示在另一個瀏覽器,並不方便
'一維條碼 128碼 呼叫程式碼
Dim b As BarcodeLib.Barcode = New BarcodeLib.Barcode()
'支援39, 128, EAN, UPC等
Dim type As BarcodeLib.TYPE = BarcodeLib.TYPE.CODE128
Try
'Me.Image1.Image = b.Encode(type, TextBox1.Text.Trim)
Dim data As String = Me.TextBox1.Text
Dim image As New System.Drawing.Bitmap(200, 200)
image = b.Encode(type, TextBox1.Text.Trim)
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif)
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
一維條碼 128碼 DLL(方法2),也是下載DLL,並加入參考
將編碼的圖片寫在另外一個.ashx 泛型處理常式中
Imports System.Web
Imports System.Web.Services
Imports System.Web.SessionState ' 要使用 Session 必需加入此命名空間
Imports System.IO
Imports System.Drawing.Imaging
Public Class barcode
Implements System.Web.IHttpHandler, IRequiresSessionState
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim encodestr As String = ""
'context.Request("encodestr") 是從傳過來的網址中抓取問號後面encoderstr的變數值
'例如 http://barcode.ashx?encodestr="123" 則會抓取123
If context.Session("encodestr") IsNot Nothing Then
'利用TryParse函數判斷使用者輸入的是數字或是文字
'If Integer.TryParse(context.Request("scid").Trim(), encoderstr) Then
'End If
encodestr = context.Session("encodestr").ToString
Dim b As BarcodeLib.Barcode = New BarcodeLib.Barcode()
Try
Dim image As New System.Drawing.Bitmap(200, 200)
'支援39, 128, EAN, UPC等,目前是將encodestr編成128碼
Dim type As BarcodeLib.TYPE = BarcodeLib.TYPE.CODE128
image = b.Encode(type, encodestr.ToString)
context.Response.ContentType = "Image/Gif"
context.Response.Clear()
image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif)
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
Else
context.Response.Write("sessioin error")
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
二維條碼 qr code DLL
https://docs.google.com/open?id=0Bxaw7Z2hq9CFa0t4dkVkMEZCOFU
'二維條碼 呼叫程式碼
Dim encoder As New ByCase.Lib.QRCode.Codec.QRCodeEncoder
'編碼有3種,分別是byte, alphanumeric, numeric
encoder.QRCodeEncodeMode = ByCase.Lib.QRCode.Codec.QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC
'(image pixels per QRCode pixel): 1, 2, 3, 4, 5, 10, 15, 30. ( in pixels )
encoder.QRCodeScale = 5
'二维码所能包含的字符信息量是由QrcodeVersion的设置值来决定的。将QrcodeVersion设置到20的时候,就已经可以容乃到300多个字节
encoder.QRCodeVersion = 20
'ByCase.Lib.QRCode.Codec.QRCodeEncoder.ERROR_CORRECTION.H L M Q
encoder.QRCodeErrorCorrect = ByCase.Lib.QRCode.Codec.QRCodeEncoder.ERROR_CORRECTION.H
'只能大寫英文, 數字, 空格+-*/冒號,不可以小寫、不可底線不可特殊符號
Dim data As String = Me.TextBox1.Text.ToUpper
Dim image As New System.Drawing.Bitmap(200, 200)
image = encoder.Encode(data)
Image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif)
二維條碼(方法2)
Google charts提供非常方便的API,可以產生QR Code圖片。
http://code.google.com/apis/chart/docs/gallery/qr_codes.html(API說明)
以下面URL為例,紅色部份為關鍵參數
https://chart.googleapis.com/chart?chs=120x120&cht=qr&chl=陳錫川&choe=UTF-8&chld=M|2
其中:
chs: QR code 圖片大小
cht: 圖片類型,google charts用這個參數產生各種圖片,這裡當然就填qr
chl: 要藏在QR code裡的文字,必須編成punycode(urlencode)。
choe: 編碼。請注意只支援iso-8859-1, sjis, utf8。詳見API說明網頁。
chld: 其他參數。M是錯誤修正層次,有L, M, Q, H等四級;後面的數字是QR code周圍白邊的寬度。
在webform放置textbox1與button,接著在button中撰寫以下程式即可
Dim imgsrc As String = "http://chart.apis.google.com/chart?chs=" & "400x400" & "&chl=" & Me.TextBox1.Text & "&choe=UTF-8&cht=qr"
Image1.ImageUrl = imgsrc
2012年12月6日 星期四
手機取消插播
最近手機電話中竟然有嘟嘟嘟的聲音,我心想是設了插播,打電話到中華電信卻說我的門號沒有設定這項功能,可能是手機自己的設定,原來
取消插播是 #43# 撥出
開啟插播是 *43# 撥出
趕緊記載blogger中
取消插播是 #43# 撥出
開啟插播是 *43# 撥出
趕緊記載blogger中
2012年10月5日 星期五
Flexsim使用sink的label屬性來收集時間統計量(最大max cycletime,最小min cycletime,平均average cycletime)
treenode item = parnode(1);
treenode current = ownerobject(c);
int port = parval(2);
{ //************* PickOption Start *************\\
/**Write to GlobalTable*/
settablenum(
/** \nTable: */ /**/"time"/**/,
/** \nRow: */ /**/getlabelnum(item, "serial")/**/,
/** \nColumn: */ /**/3/**/,
/** \nValue: */ /**/time()/**/
);
/**\n\n*/
} //******* PickOption End *******\\
{ //************* PickOption Start *************\\
/**Set Label*/
setlabelnum(
/** \nObject: */ /**/item/**/,
/** \nLabel: */ /**/"outtime"/**/,
/** \nValue: */ /**/time()/**/
);
/**\n\n*/
} //******* PickOption End *******\\
{ //************* PickOption Start *************\\
/**Set Label*/
setlabelnum(
/** \nObject: */ /**/item/**/,
/** \nLabel: */ /**/"cycletime"/**/,
/** \nValue: */ /**/getlabelnum(item, "outtime")-getlabelnum(item, "intime")/**/
);
/**\n\n*/
} //******* PickOption End *******\\
//收集累積的 cycle time
{ //************* PickOption Start *************\\
/**Set Label*/
setlabelnum(
/** \nObject: */ /**/current/**/,
/** \nLabel: */ /**/"accumulatedct"/**/,
/** \nValue: */ /**/getlabelnum(item,"cycletime")+getlabelnum(current, "accumulatedct")/**/
);
/**\n\n*/
} //******* PickOption End *******\\
//收集最小cycle time
if (getlabelnum(item, "serial") == 1)
{
setlabelnum(current,"minct", getlabelnum(item,"cycletime"));
}
else
{
if (getlabelnum(current, "minct") > getlabelnum(item, "cycletime"))
{
setlabelnum(current,"minct", getlabelnum(item,"cycletime"));
}
}
//收集最大cycle time
if (getlabelnum(item, "serial") == 1)
{
setlabelnum(current,"maxct", getlabelnum(item,"cycletime"));
}
else
{
if (getlabelnum(current, "maxct") < getlabelnum(item, "cycletime"))
{
setlabelnum(current,"maxct", getlabelnum(item,"cycletime"));
}
}
{ //************* PickOption Start *************\\
//收集個數totalnum
/**Increment Value*/
inc(
/** \nNode: */ /**/label(current, "totalnum")/**list:label(item, "labelname")~gettablecell("tablename", 1,1)~node("/Tools/myvalue",model())*/
,
/** \nIncrement By: */ /**/1/**/
);
/**\n\n*/
} //******* PickOption End *******\\
{ //************* PickOption Start *************\\
//計算平均的cycle time: avgct,將累積的cycletime除以個數
/**Set Label*/
setlabelnum(
/** \nObject: */ /**/current/**/,
/** \nLabel: */ /**/"avgct"/**/,
/** \nValue: */ /**/getlabelnum(current,"accumulatedct")/getlabelnum(current,"totalnum")/**/
);
/**\n\n*/
} //******* PickOption End *******\\
flexsim收集全部個體的開始時間, 離開等候線時間,及 離開系統時間
收集Flexsim的時間我設計了兩種方法,第一種方法是每個個體的時間都收集,並export到excel做分析,做法是採用global table來收集,最後在export出去。
2012年10月1日 星期一
2012年9月28日 星期五
Excel 2010 運輸問題求解範例(線性規劃)
從網路上找到一個運輸問題的範例,http://www.google.com.tw/url?sa=t&rct=j&q=&esrc=s&frm=1&source=web&cd=1&cad=rja&ved=0CCIQFjAA&url=http%3A%2F%2Fcc.cust.edu.tw%2F~thchu%2FLMex%2FLMLP446question.XLS&ei=-E1mUJ_hE4bGmQWE24GQCQ&usg=AFQjCNEHcLj9YRZrmQKWtkfy1pMMJPqi2g&sig2=EXJalK0d4zkRe7QW4fTGIA
我做了一些修改,加上需求量、供給量 與 距離。
運輸問題是以最低的運輸費用將貨品從工廠送到最接近市場需求中心的倉庫。各工廠必須在出貨量不超出供應量的前提下,同時也要達到滿足每一個市場的需求目的。
我做了一些修改,加上需求量、供給量 與 距離。
運輸問題是以最低的運輸費用將貨品從工廠送到最接近市場需求中心的倉庫。各工廠必須在出貨量不超出供應量的前提下,同時也要達到滿足每一個市場的需求目的。
Visio畫直線,取消跨線跳線跳轉
自從改用2010後,很多功能找不到,只能慢慢熟悉了,例如在Visio 2010中,要畫直線,一般預設的連接器會自動折線(自動直角),可是我們常有畫直線的需求,其實這個設定就在
設計/連接器/直線 ,或者要取消跨線 或稱為取消跳線 的功能,同樣在 設計/連接器/取消顯示線條跳轉 即可。
2012年9月27日 星期四
圖片縮圖
3002/30025.aspx 負責處理圖片縮圖
' 取得圖型資料及縮圖處理
' FileUpload 的檔案內容存入 Image
Using img_tmp As System.Drawing.Image = System.Drawing.Image.FromFile(fullname)
ac_height = img_tmp.Height
' 實際高度
ac_width = img_tmp.Width
' 實際寬度
' 維持圖檔比例的方式,計算與縮圖 120 * 120 的比例
If ac_width > ac_height Then
fCnt = ac_width / 120.0R
Else
fCnt = ac_height / 120.0R
End If
' 實際圖比縮圖大時才要處理,否則仍為原圖檔尺寸
If fCnt > 1 Then
s_width = CInt((ac_width / fCnt))
' 縮圖寬度
' 縮圖高度
s_height = CInt((ac_height / fCnt))
Else
s_width = ac_width
' 縮圖寬度
' 縮圖高度
s_height = ac_height
End If
' 呼叫 Bitmap 物件的 GetThumbnailImage 方法來建立一個縮圖
Using img_thumb As System.Drawing.Image = img_tmp.GetThumbnailImage(s_width, s_height, Nothing, IntPtr.Zero)
fullname = lb_path.Text & "_thumb\" & fname & ".jpg"
' 縮圖的壓縮比為 75%
Dim eps As New EncoderParameters()
eps.Param(0) = New EncoderParameter(Encoder.Quality, CLng(75))
' 以預設壓縮比儲存 jpeg (75%)
' img_thumb.Save(fullname, System.Drawing.Imaging.ImageFormat.Jpeg);
img_thumb.Save(fullname, GetEncoderInfo("image/jpeg"), eps)
End Using
End Using
-------------------------------------------------------
'網路上找到的資料
using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using Microsoft.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ItemUpdating(object sender, IOrderedDictionary newData, IOrderedDictionary oldData)
{
try
{
FileUpload fileUpload = (FileUpload)((DetailsView)sender).FindControl( "FileUpload ");
//e.Values.
if (fileUpload.HasFile)
{
newData[ "MIME_TYPE "] = Server.HtmlEncode(fileUpload.PostedFile.ContentType);
newData[ "FILESIZE "] = fileUpload.PostedFile.ContentLength;
newData[ "FILENAME "] = Server.HtmlEncode(Path.GetFileName(fileUpload.PostedFile.FileName));
byte[] b = fileUpload.FileBytes;
byte[] bThumb = CreateThumbnail(b);
newData[ "THUMBNAIL "] = bThumb;
newData[ "ASSETFILE "] = b;
return;
}
if(oldData!=null)
{
newData[ "MIME_TYPE "] = oldData[ "MIME_TYPE "];
newData[ "FILESIZE "] = oldData[ "FILESIZE "] ;
newData[ "FILENAME "] = oldData[ "FILENAME "] ;
DictationDataSet ds = new DictationDataSet();
DictationDataSetTableAdapters.DICTATIONTableAdapter da = new DictationDataSetTableAdapters.DICTATIONTableAdapter(); ;
da.Fill(ds.DICTATION);
DataRow[] drs = ds.DICTATION.Select( "ID= " + ((DetailsView)sender).DataKey.Value.ToString());
DataRow dr = drs[0];
newData[ "THUMBNAIL "] = (byte[])dr[ "THUMBNAIL "];
newData[ "ASSETFILE "] = (byte[])dr[ "ASSETFILE "];
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void DetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
ItemUpdating(sender, e.NewValues,e.OldValues);
}
protected void DetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
ItemUpdating(sender, e.Values,null);
}
static public byte[] CreateThumbnail(byte[] src)
{
try
{
System.Drawing.Image img = System.Drawing.Image.FromStream(new MemoryStream(src));
System.Drawing.Image imgthumb = img.GetThumbnailImage(100, 75, null, new System.IntPtr(0));
MemoryStream thumbstream=new MemoryStream();
imgthumb.Save(thumbstream, ImageFormat.Jpeg);
img.Dispose();
byte[] b=thumbstream.ToArray();
imgthumb.Dispose();
return b;
}
catch (Exception e)
{
}
return null;
}
protected void DetailsView_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
RebindGrid();
}
protected void DetailsView_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
RebindGrid();
}
protected void DetailsView_ItemDeleted(object sender, DetailsViewDeletedEventArgs e)
{
RebindGrid();
}
void RebindGrid()
{
this.GridView.DataBind();
}
protected void GridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
this.DetailsView.ChangeMode(DetailsViewMode.Edit);
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
FileUpload fileUpload = (FileUpload)((DetailsView)this.DetailsView).FindControl( "FileUpload ");
if (fileUpload.HasFile)
{
HttpRuntimeSection config1 = new HttpRuntimeSection();
int num1 = (config1 != null) ? config1.MaxRequestLength : 0x400000;
args.IsValid = (fileUpload.PostedFile.ContentLength > num1);
}
}
}
-------------------------------------------------------
'網路上找到的資料
'有一个vb的
'生成缩略图
Sub MakeThumbnail(ByVal originalImagePath As String, ByVal thumbnailPath As String, ByVal width As Integer, ByVal height As Integer, ByVal mode As String)
Dim originalImage = System.Drawing.Image.FromFile(originalImagePath)
Dim towidth As Integer = width
Dim toheight As Integer = height
Dim x As Integer = 0
Dim y As Integer = 0
Dim ow As Integer = originalImage.Width
Dim oh As Integer = originalImage.Height
Select Case (mode)
Case "HW " '指定高宽缩放(可能变形)
Case "W " '指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width
Case "H " '指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height
Case "Cut " '指定高宽裁减(不变形)
If (CType(originalImage.Width, Double) / CType(originalImage.Height, Double)) > (CType(towidth, Double) / CType(toheight, Double)) Then
oh = originalImage.Height
ow = originalImage.Height * towidth / toheight
y = 0
x = (originalImage.Width - ow) / 2
Else
ow = originalImage.Width
oh = originalImage.Width * height / towidth
x = 0
y = (originalImage.Height - oh) / 2
End If
End Select
'新建一个bmp图片
Dim bitmap = New System.Drawing.Bitmap(towidth, toheight)
'新建一个画板
Dim g = System.Drawing.Graphics.FromImage(bitmap)
'设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High
'设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
'清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent)
'在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, New System.Drawing.Rectangle(0, 0, towidth, toheight), New System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel)
Try
'以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg)
Catch ex As Exception
Throw ex
Finally
originalImage.Dispose()
bitmap.Dispose()
g.Dispose()
End Try
End Sub
後來網路上又找到呼叫另外軟體來做縮圖的
http://www.dotblogs.com.tw/killysss/archive/2011/06/20/29257.aspx?fid=30793#feedback
' 取得圖型資料及縮圖處理
' FileUpload 的檔案內容存入 Image
Using img_tmp As System.Drawing.Image = System.Drawing.Image.FromFile(fullname)
ac_height = img_tmp.Height
' 實際高度
ac_width = img_tmp.Width
' 實際寬度
' 維持圖檔比例的方式,計算與縮圖 120 * 120 的比例
If ac_width > ac_height Then
fCnt = ac_width / 120.0R
Else
fCnt = ac_height / 120.0R
End If
' 實際圖比縮圖大時才要處理,否則仍為原圖檔尺寸
If fCnt > 1 Then
s_width = CInt((ac_width / fCnt))
' 縮圖寬度
' 縮圖高度
s_height = CInt((ac_height / fCnt))
Else
s_width = ac_width
' 縮圖寬度
' 縮圖高度
s_height = ac_height
End If
' 呼叫 Bitmap 物件的 GetThumbnailImage 方法來建立一個縮圖
Using img_thumb As System.Drawing.Image = img_tmp.GetThumbnailImage(s_width, s_height, Nothing, IntPtr.Zero)
fullname = lb_path.Text & "_thumb\" & fname & ".jpg"
' 縮圖的壓縮比為 75%
Dim eps As New EncoderParameters()
eps.Param(0) = New EncoderParameter(Encoder.Quality, CLng(75))
' 以預設壓縮比儲存 jpeg (75%)
' img_thumb.Save(fullname, System.Drawing.Imaging.ImageFormat.Jpeg);
img_thumb.Save(fullname, GetEncoderInfo("image/jpeg"), eps)
End Using
End Using
-------------------------------------------------------
'網路上找到的資料
using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using Microsoft.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ItemUpdating(object sender, IOrderedDictionary newData, IOrderedDictionary oldData)
{
try
{
FileUpload fileUpload = (FileUpload)((DetailsView)sender).FindControl( "FileUpload ");
//e.Values.
if (fileUpload.HasFile)
{
newData[ "MIME_TYPE "] = Server.HtmlEncode(fileUpload.PostedFile.ContentType);
newData[ "FILESIZE "] = fileUpload.PostedFile.ContentLength;
newData[ "FILENAME "] = Server.HtmlEncode(Path.GetFileName(fileUpload.PostedFile.FileName));
byte[] b = fileUpload.FileBytes;
byte[] bThumb = CreateThumbnail(b);
newData[ "THUMBNAIL "] = bThumb;
newData[ "ASSETFILE "] = b;
return;
}
if(oldData!=null)
{
newData[ "MIME_TYPE "] = oldData[ "MIME_TYPE "];
newData[ "FILESIZE "] = oldData[ "FILESIZE "] ;
newData[ "FILENAME "] = oldData[ "FILENAME "] ;
DictationDataSet ds = new DictationDataSet();
DictationDataSetTableAdapters.DICTATIONTableAdapter da = new DictationDataSetTableAdapters.DICTATIONTableAdapter(); ;
da.Fill(ds.DICTATION);
DataRow[] drs = ds.DICTATION.Select( "ID= " + ((DetailsView)sender).DataKey.Value.ToString());
DataRow dr = drs[0];
newData[ "THUMBNAIL "] = (byte[])dr[ "THUMBNAIL "];
newData[ "ASSETFILE "] = (byte[])dr[ "ASSETFILE "];
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void DetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
ItemUpdating(sender, e.NewValues,e.OldValues);
}
protected void DetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
ItemUpdating(sender, e.Values,null);
}
static public byte[] CreateThumbnail(byte[] src)
{
try
{
System.Drawing.Image img = System.Drawing.Image.FromStream(new MemoryStream(src));
System.Drawing.Image imgthumb = img.GetThumbnailImage(100, 75, null, new System.IntPtr(0));
MemoryStream thumbstream=new MemoryStream();
imgthumb.Save(thumbstream, ImageFormat.Jpeg);
img.Dispose();
byte[] b=thumbstream.ToArray();
imgthumb.Dispose();
return b;
}
catch (Exception e)
{
}
return null;
}
protected void DetailsView_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
RebindGrid();
}
protected void DetailsView_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
RebindGrid();
}
protected void DetailsView_ItemDeleted(object sender, DetailsViewDeletedEventArgs e)
{
RebindGrid();
}
void RebindGrid()
{
this.GridView.DataBind();
}
protected void GridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
this.DetailsView.ChangeMode(DetailsViewMode.Edit);
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
FileUpload fileUpload = (FileUpload)((DetailsView)this.DetailsView).FindControl( "FileUpload ");
if (fileUpload.HasFile)
{
HttpRuntimeSection config1 = new HttpRuntimeSection();
int num1 = (config1 != null) ? config1.MaxRequestLength : 0x400000;
args.IsValid = (fileUpload.PostedFile.ContentLength > num1);
}
}
}
-------------------------------------------------------
'網路上找到的資料
'有一个vb的
'生成缩略图
Sub MakeThumbnail(ByVal originalImagePath As String, ByVal thumbnailPath As String, ByVal width As Integer, ByVal height As Integer, ByVal mode As String)
Dim originalImage = System.Drawing.Image.FromFile(originalImagePath)
Dim towidth As Integer = width
Dim toheight As Integer = height
Dim x As Integer = 0
Dim y As Integer = 0
Dim ow As Integer = originalImage.Width
Dim oh As Integer = originalImage.Height
Select Case (mode)
Case "HW " '指定高宽缩放(可能变形)
Case "W " '指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width
Case "H " '指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height
Case "Cut " '指定高宽裁减(不变形)
If (CType(originalImage.Width, Double) / CType(originalImage.Height, Double)) > (CType(towidth, Double) / CType(toheight, Double)) Then
oh = originalImage.Height
ow = originalImage.Height * towidth / toheight
y = 0
x = (originalImage.Width - ow) / 2
Else
ow = originalImage.Width
oh = originalImage.Width * height / towidth
x = 0
y = (originalImage.Height - oh) / 2
End If
End Select
'新建一个bmp图片
Dim bitmap = New System.Drawing.Bitmap(towidth, toheight)
'新建一个画板
Dim g = System.Drawing.Graphics.FromImage(bitmap)
'设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High
'设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
'清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent)
'在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, New System.Drawing.Rectangle(0, 0, towidth, toheight), New System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel)
Try
'以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg)
Catch ex As Exception
Throw ex
Finally
originalImage.Dispose()
bitmap.Dispose()
g.Dispose()
End Try
End Sub
後來網路上又找到呼叫另外軟體來做縮圖的
http://www.dotblogs.com.tw/killysss/archive/2011/06/20/29257.aspx?fid=30793#feedback
app_code資料夾的使用_圖形驗證數字
最近研究章立民研究室所出的書,其中有一章節提到圖形驗證(圖文驗證)的機制,可是該書籍的光碟使用讓人並不容易了解,我載入圖文驗證的網站是編譯都發生錯誤,畫面如下,後來去 1002.aspx.vb 找,果然有這行指令,在該檔案內也找不到 common_func() 相關的資料,後來發現原來在 網站內有一個app_code資料夾,該資料夾內有Common_Func.vb這個檔案,上網查了app_code資料夾,原來這種app_code資料夾主要是儲存共用程式碼,以前好像曾經用過,記憶已經退化了,所以要在原本的網站內按右鍵加入ASP.NET資料夾,選app_code,接著將common_func.vb複製進去,該錯誤就解決了,但出現了另外的錯誤,按照相同的方式,總共複製了 common_func.vb, string_func.vb, decoder.vb 。本以為解決了,結果瀏覽器還是出現Not Found的錯誤,不死心接著在visual studio 建置/建置方案,發現有一個BuildImage未定義的錯誤,於是用相同的方法,找到 BuildImage.vb ,並複製到app_code資料夾,終於成功看到圖文驗證的畫面了。
好不容易看到圖文驗證的畫面,怎麼有一種數字出不來,原來該數字是從預設的圖片來顯示的,終於在 BuildImage.vb 內找到了圖片所在位置 /images/confirm/ 內,將整個資料夾複製到我們的網站內終於正常顯示了。
2012年9月26日 星期三
下載或刪除儲存在資料庫的檔案_ashx泛型處理常式
使用泛型處理常式 download.ashx 來下載儲存於資料庫欄位中的資料。
此檔案會從被呼叫的網址收集scid參數,當成資料庫下載的主要鍵
<%@ WebHandler Language="VB" Class="download" %>
'----------------------------------------------------------------------------
'程式功能 檔案上傳下載 (以資料庫存放檔案) > 檔案下載
'----------------------------------------------------------------------------
Imports System
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.Configuration
Imports System.Web.SessionState ' 要使用 Session 必需加入此命名空間
Public Class download : Implements IHttpHandler, IRequiresSessionState
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/plain"
'context.Response.Write("Hello World")
Dim mErr As String = ""
Dim scid2 As Integer = -1
' 檢查使用者權限,但不存入登入紀錄
'Check_Power("2002", False, context)
If context.Request("scid") IsNot Nothing Then
If Integer.TryParse(context.Request("scid").Trim(), scid2) Then
' 處理下載檔案
Using Sql_conn As New SqlConnection(WebConfigurationManager.ConnectionStrings("AppSysConnectionString").ConnectionString)
Sql_conn.Open()
Using Sql_Command As New SqlCommand()
Dim SqlString As String = ""
SqlString = "Select Top 1 fname, ftype, fcontent From 學生證照2 Where scid2 = @scid2"
Sql_Command.Connection = Sql_conn
Sql_Command.CommandText = SqlString
Sql_Command.Parameters.AddWithValue("scid2", scid2)
Dim Sql_Reader As SqlDataReader = Sql_Command.ExecuteReader()
If Sql_Reader.Read() Then
Dim fcontent As Byte() = DirectCast(Sql_Reader("fcontent"), Byte())
context.Response.Clear()
context.Response.Charset = "utf-8"
' 檔名要先編碼,中文檔名才不會有問題
context.Response.AddHeader("Content-Disposition", "inline;filename=" & context.Server.UrlEncode(Sql_Reader("fname").ToString().Trim()))
context.Response.ContentType = Sql_Reader("ftype").ToString()
context.Response.BinaryWrite(fcontent)
context.Response.End()
Else
mErr = "找不到這個檔案的資料!\n"
End If
End Using
End Using
Else
mErr = "參數傳送有問題!\n"
End If
Else
mErr = "參數傳送有問題!\n"
End If
If mErr <> "" Then
context.Response.ContentType = "text/html"
context.Response.Write(mErr)
context.Response.End()
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
而另外有一個 filedelete_download.aspx 來呼叫剛剛撰寫的 download.ashx 。
此檔案會從被呼叫的網址收集scid參數,當成資料庫下載的主要鍵
<%@ WebHandler Language="VB" Class="download" %>
'----------------------------------------------------------------------------
'程式功能 檔案上傳下載 (以資料庫存放檔案) > 檔案下載
'----------------------------------------------------------------------------
Imports System
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.Configuration
Imports System.Web.SessionState ' 要使用 Session 必需加入此命名空間
Public Class download : Implements IHttpHandler, IRequiresSessionState
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/plain"
'context.Response.Write("Hello World")
Dim mErr As String = ""
Dim scid2 As Integer = -1
' 檢查使用者權限,但不存入登入紀錄
'Check_Power("2002", False, context)
If context.Request("scid") IsNot Nothing Then
If Integer.TryParse(context.Request("scid").Trim(), scid2) Then
' 處理下載檔案
Using Sql_conn As New SqlConnection(WebConfigurationManager.ConnectionStrings("AppSysConnectionString").ConnectionString)
Sql_conn.Open()
Using Sql_Command As New SqlCommand()
Dim SqlString As String = ""
SqlString = "Select Top 1 fname, ftype, fcontent From 學生證照2 Where scid2 = @scid2"
Sql_Command.Connection = Sql_conn
Sql_Command.CommandText = SqlString
Sql_Command.Parameters.AddWithValue("scid2", scid2)
Dim Sql_Reader As SqlDataReader = Sql_Command.ExecuteReader()
If Sql_Reader.Read() Then
Dim fcontent As Byte() = DirectCast(Sql_Reader("fcontent"), Byte())
context.Response.Clear()
context.Response.Charset = "utf-8"
' 檔名要先編碼,中文檔名才不會有問題
context.Response.AddHeader("Content-Disposition", "inline;filename=" & context.Server.UrlEncode(Sql_Reader("fname").ToString().Trim()))
context.Response.ContentType = Sql_Reader("ftype").ToString()
context.Response.BinaryWrite(fcontent)
context.Response.End()
Else
mErr = "找不到這個檔案的資料!\n"
End If
End Using
End Using
Else
mErr = "參數傳送有問題!\n"
End If
Else
mErr = "參數傳送有問題!\n"
End If
If mErr <> "" Then
context.Response.ContentType = "text/html"
context.Response.Write(mErr)
context.Response.End()
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
而另外有一個 filedelete_download.aspx 來呼叫剛剛撰寫的 download.ashx 。
傳遞網址 download.ashx?scid={0} {0}代表的是DataNavigateUrlField的資料,也就是資料表中的主要鍵欄位。
點選下載後,如果是圖形會直接開新視窗顯示圖片,如果是其他檔案會詢問開啟, 儲存 或 取消
當我們要實作刪除功能時,首先必須修改 sqldatasource ,設定sqldatasource資料來源時,刪除delete指令需要修改,改成
DELETE FROM [學生證照2] WHERE [scid2] = @original_scid2
接著從 gridview 啟用刪除即可,必要時可用編輯資料行調整左右位置
檔案上傳asp.net
檔案上傳一直是教書以來想要完成的事,可是大部分的書都叫讀者上傳到伺服器的某個資料夾儲存,這會是一個嚴重的問題。這學期教資料庫剛好複習一下,這次使用Visaul Studio 2010,是 ASP.NET 4.0,應該可以用個幾年吧。
1. 首先在設計模式布置FileUpload(負責選取檔案), textbox(負責輸入檔案描述,可空白),Button(負責驅動上傳), Literal(負責上傳後顯示資訊),而Label物件可以不用放。
而對應要儲存檔案的資料表設計如下, fcontent負責儲存檔案內容,ftype負責檔案類型,fsize檔案大小,fname檔案全名(包括附檔名),fext負責附檔名,fdesc是檔案的描述說明, fuploadtiem存上傳的日期時間。
而程式碼uploadfile.aspx.vb的內容如下
Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.IO
Partial Class Default4
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim icnt As Integer = 0, jcnt As Integer = 0
Dim sqlstring As String = "", merr As String = ""
Dim fname As String = "", fext As String = "", ftype As String = "", fsize As Integer = 0, fdesc As String = "", fuploadtime As DateTime = DateTime.Now
'處理上傳檔案、說明及檔案內容存入資料庫
Using sql_conn As New SqlConnection(WebConfigurationManager.ConnectionStrings("APPSYSConnectionString").ConnectionString)
sql_conn.Open()
Using sql_command As New SqlCommand()
'儲存檔案
'For icnt = 1 To Request.Files.Count
Dim fu_file As FileUpload = DirectCast(Page.FindControl("fu_file"), FileUpload)
Dim tb_file As TextBox = DirectCast(Page.FindControl("tb_file"), TextBox)
If fu_file.HasFile Then
jcnt = jcnt + 1
fname = fu_file.FileName
fext = Path.GetExtension(fname).ToString()
fsize = fu_file.PostedFile.ContentLength
Response.Write(fsize)
If fsize > 1024000 Then
merr = "檔案超過1MB"
End If
ftype = fu_file.PostedFile.ContentType
fdesc = tb_file.Text.Trim()
'檔案存入資料庫
sqlstring = "insert into 學生證照2 " & "(fname, fext, ftype, fsize, fdesc, fcontent, fuploadtime)"
sqlstring &= " values (@fname, @fext, @ftype, @fsize, @fdesc, @fcontent, @fuploadtime)"
sql_command.Parameters.Clear()
sql_command.CommandText = sqlstring
sql_command.Connection = sql_conn
sql_command.Parameters.AddWithValue("fname", fname)
sql_command.Parameters.AddWithValue("fext", fext.ToLower())
sql_command.Parameters.AddWithValue("ftype", ftype)
sql_command.Parameters.AddWithValue("fsize", fsize)
sql_command.Parameters.AddWithValue("fdesc", fdesc)
'fuploadtime是以client的系統時間為準
sql_command.Parameters.AddWithValue("fuploadtime", fuploadtime)
sql_command.Parameters.AddWithValue("fcontent", fu_file.FileBytes)
If merr = "" Then
sql_command.ExecuteNonQuery()
End If
Else
merr = "沒有選擇任何上傳的檔案!"
End If
' Next
End Using
End Using
'msg_close()呼叫寫在aspx的javascript副程式,javascript必須寫在<head>與</head>中間
'為了減少複雜性,我將msg_close()的指令去掉了
If merr <> "" Then
'顯示錯誤訊息
lt_show.Text = "<script language=javascript>alert(""" & merr & """);</script>"
Else
'完成上傳,返回瀏覽頁
lt_show.Text = "<script language=javascript>alert(""資料上傳完成!\n"");location.replace(""filedelete_download.aspx"");</script>"
'lt_show.Text &= "location.replace(""Default5.aspx"");</script>"
End If
End Sub
End Class
另外要一提的是預設上傳檔案有大小限制,經過測試約在4MB左右,
因此在web.config <system.web>與 </system.web>之間,加上此行程式(改變上限為10MB) <httpRuntime maxRequestLength="10240"/>
如果超過10MB,瀏覽器的畫面會出現無法顯示網頁
為了避免此畫面,所以網頁可以允許上傳<1MB的檔案,但因為原本uploadfile.aspx.vb中,有小於1MB的條件
If fsize > 1024000 Then
merr = "檔案超過1MB"
End If
除了檔案大小外,也可透過限制使用者上傳檔案的附檔名來避免發生太大的檔案,可以google查到使用java script來限制,將原本uploadfile.aspx的html修改,從原本
<asp:FileUpload ID="fu_file" runat="server" /> 改成
<asp:FileUpload ID="fu_file" runat="server" onchange="return checkFileExtension(this);"/>
此外,將下列指令放在 uploadfile.aspx 原始檔<head>與</head>中,
<script type="text/javascript">
function checkFileExtension(elem) {
var filePath = elem.value;
if (filePath.indexOf('.') == -1) {
remove(elem);
alert('不正確的副檔名格式');
return false;
}
var validExtensions = new Array();
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
//限制只能選取那些副檔名
validExtensions[0] = 'jpg';
validExtensions[1] = 'pdf';
validExtensions[2] = 'doc';
validExtensions[3] = 'docx';
validExtensions[4] = 'jpeg';
for (var i = 0; i < validExtensions.length; i++) {
if (ext == validExtensions[i])
return true;
}
remove(elem);
alert('不正確的副檔名格式: ' + ext.toUpperCase());
return false;
}
function remove(control) {
var who = control;
who.value = "";
var who2 = who.cloneNode(false);
who2.onchange = who.onchange;
who.parentNode.replaceChild(who2, who);
}
</script>
1. 首先在設計模式布置FileUpload(負責選取檔案), textbox(負責輸入檔案描述,可空白),Button(負責驅動上傳), Literal(負責上傳後顯示資訊),而Label物件可以不用放。
而對應要儲存檔案的資料表設計如下, fcontent負責儲存檔案內容,ftype負責檔案類型,fsize檔案大小,fname檔案全名(包括附檔名),fext負責附檔名,fdesc是檔案的描述說明, fuploadtiem存上傳的日期時間。
而程式碼uploadfile.aspx.vb的內容如下
Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.IO
Partial Class Default4
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim icnt As Integer = 0, jcnt As Integer = 0
Dim sqlstring As String = "", merr As String = ""
Dim fname As String = "", fext As String = "", ftype As String = "", fsize As Integer = 0, fdesc As String = "", fuploadtime As DateTime = DateTime.Now
'處理上傳檔案、說明及檔案內容存入資料庫
Using sql_conn As New SqlConnection(WebConfigurationManager.ConnectionStrings("APPSYSConnectionString").ConnectionString)
sql_conn.Open()
Using sql_command As New SqlCommand()
'儲存檔案
'For icnt = 1 To Request.Files.Count
Dim fu_file As FileUpload = DirectCast(Page.FindControl("fu_file"), FileUpload)
Dim tb_file As TextBox = DirectCast(Page.FindControl("tb_file"), TextBox)
If fu_file.HasFile Then
jcnt = jcnt + 1
fname = fu_file.FileName
fext = Path.GetExtension(fname).ToString()
fsize = fu_file.PostedFile.ContentLength
Response.Write(fsize)
If fsize > 1024000 Then
merr = "檔案超過1MB"
End If
ftype = fu_file.PostedFile.ContentType
fdesc = tb_file.Text.Trim()
'檔案存入資料庫
sqlstring = "insert into 學生證照2 " & "(fname, fext, ftype, fsize, fdesc, fcontent, fuploadtime)"
sqlstring &= " values (@fname, @fext, @ftype, @fsize, @fdesc, @fcontent, @fuploadtime)"
sql_command.Parameters.Clear()
sql_command.CommandText = sqlstring
sql_command.Connection = sql_conn
sql_command.Parameters.AddWithValue("fname", fname)
sql_command.Parameters.AddWithValue("fext", fext.ToLower())
sql_command.Parameters.AddWithValue("ftype", ftype)
sql_command.Parameters.AddWithValue("fsize", fsize)
sql_command.Parameters.AddWithValue("fdesc", fdesc)
'fuploadtime是以client的系統時間為準
sql_command.Parameters.AddWithValue("fuploadtime", fuploadtime)
sql_command.Parameters.AddWithValue("fcontent", fu_file.FileBytes)
If merr = "" Then
sql_command.ExecuteNonQuery()
End If
Else
merr = "沒有選擇任何上傳的檔案!"
End If
' Next
End Using
End Using
'msg_close()呼叫寫在aspx的javascript副程式,javascript必須寫在<head>與</head>中間
'為了減少複雜性,我將msg_close()的指令去掉了
If merr <> "" Then
'顯示錯誤訊息
lt_show.Text = "<script language=javascript>alert(""" & merr & """);</script>"
Else
'完成上傳,返回瀏覽頁
lt_show.Text = "<script language=javascript>alert(""資料上傳完成!\n"");location.replace(""filedelete_download.aspx"");</script>"
'lt_show.Text &= "location.replace(""Default5.aspx"");</script>"
End If
End Sub
End Class
另外要一提的是預設上傳檔案有大小限制,經過測試約在4MB左右,
因此在web.config <system.web>與 </system.web>之間,加上此行程式(改變上限為10MB) <httpRuntime maxRequestLength="10240"/>
如果超過10MB,瀏覽器的畫面會出現無法顯示網頁
為了避免此畫面,所以網頁可以允許上傳<1MB的檔案,但因為原本uploadfile.aspx.vb中,有小於1MB的條件
If fsize > 1024000 Then
merr = "檔案超過1MB"
End If
除了檔案大小外,也可透過限制使用者上傳檔案的附檔名來避免發生太大的檔案,可以google查到使用java script來限制,將原本uploadfile.aspx的html修改,從原本
<asp:FileUpload ID="fu_file" runat="server" /> 改成
<asp:FileUpload ID="fu_file" runat="server" onchange="return checkFileExtension(this);"/>
此外,將下列指令放在 uploadfile.aspx 原始檔<head>與</head>中,
<script type="text/javascript">
function checkFileExtension(elem) {
var filePath = elem.value;
if (filePath.indexOf('.') == -1) {
remove(elem);
alert('不正確的副檔名格式');
return false;
}
var validExtensions = new Array();
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
//限制只能選取那些副檔名
validExtensions[0] = 'jpg';
validExtensions[1] = 'pdf';
validExtensions[2] = 'doc';
validExtensions[3] = 'docx';
validExtensions[4] = 'jpeg';
for (var i = 0; i < validExtensions.length; i++) {
if (ext == validExtensions[i])
return true;
}
remove(elem);
alert('不正確的副檔名格式: ' + ext.toUpperCase());
return false;
}
function remove(control) {
var who = control;
who.value = "";
var who2 = who.cloneNode(false);
who2.onchange = who.onchange;
who.parentNode.replaceChild(who2, who);
}
</script>
訂閱:
文章 (Atom)