我又問了一個關于 Ajax 檔案上傳的問題.. T_T
我有一個使用 Ajax 檔案上傳的 ASP.NET 網路表單(使用 VB.NET)。每當我上傳檔案時,我都會更新我的資料庫表。當我拖入上傳面板并單擊上傳按鈕時,我正在檢查檔案是否已上傳。如果目標檔案已經上傳,我想顯示我的錯誤標簽,如 'the file is already upload' 。但是標簽沒有顯示。我進行了除錯以跟蹤結果,該檔案確實存在,它通過了我的標簽文本設定,但沒有顯示在我的表單上。我的代碼的哪一部分是錯誤的?我希望有人可以指導我。
這是我的asp代碼
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
//customize the drag panel
function AjaxFileUpload_change_text() {
Sys.Extended.UI.Resources.AjaxFileUpload_Upload = "Click Upload";
document.getElementsByClassName('ajax__fileupload_uploadbutton')[0].style.width = '100px';
}
</script>
<div style="width:40%;padding:25px;margin-left:200px">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384" AllowedFileTypes="pdf" MaximumNumberOfFiles="10" />
<asp:Button ID="cmdDone" runat="server" Text="Done" style="display:none" ClientIDMode="Static" />
<script>
function MyCompleteAll() {
$('cmdDone').click()
}
</script>
</div>
<asp:Label ID="lblmsg" runat="server" Text="" Width ="150px" style="color:red"></asp:Label><br />
</asp:Content>
.vb 代碼
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ClientScript.RegisterStartupScript(Page.GetType(), "OnLoad", "AjaxFileUpload_change_text();", True) //customize ajax panel
lblmsg.Text = "" //error display
End Sub
Protected Sub MyCompleteAll(sender As Object, e As AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim filename As String = e.FileName.Split(".").First "_" fileupload ".pdf"
Dim path As String = Server.MapPath("~/uploads/")
//to add a database table of files up-loaded.
Dim constr As String = CONN g_schema
Using con As New MySqlConnection(constr)
con.Open()
'check file is already uploaded
Dim select_seq As String = "select fname from filetable where fname like '"
e.FileName.Split(".").First "%'"
Dim cmd As New MySqlCommand(select_seq, con)
Dim reader = cmd.ExecuteReader()
While reader.Read()
fname = reader(0).ToString
End While
con.Close()
//the file is already uploaded
If fname IsNot "" Then
lblmsg.Text = "Already uploaded. Please upload the other files."
Else
// Upload process code
End Sub
謝謝你。
uj5u.com熱心網友回復:
我建議您在檔案上傳完成事件中檢查檔案。
因此,我們可以建立一個存在的檔案串列 - 您有可能上傳多個檔案。
所以,我建議放入一個文本框來“保存”每個壞(重復)檔案。
因此,讓我們將重復檔案持久保存到 session() 中(我們不能在 3 個事件(開始、完成、全部完成)中使用頁面上的控制元件。
所以,我們有這個代碼:
Dim DupList As New List(Of String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Session("DupList") = DupList
txtDups.Visible = False
Else
DupList = Session("DupList")
End If
End Sub
并說出這個標記 - 文本框、網格視圖,當然還有 FileUpload。
所以,說這個標記:
<div style="width:40%;padding:25px">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384"
/>
<asp:Button ID="cmdDone" runat="server" Text="Done"
style="display:none" ClientIDMode="Static"/>
<asp:TextBox ID="txtDups" runat="server" TextMode="MultiLine" Width="523px"></asp:TextBox>
<script>
function MyCompleteAll() {
$('#cmdDone').click()
}
</script>
<asp:GridView ID="Gfiles" runat="server" CssClass="table" DataKeyNames="ID"></asp:GridView>
</div>
到目前為止 - 非常好,您可以單擊 JavaScript 按鈕以在完成后回傳我們非常重要且需要的最終帖子。
因此,單個檔案上傳完成事件 - 如下所示:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
' now code to add say to a database table of files up-loaded.
' but FIRST CHECK if the file already exists
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = @F"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("@F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then
' the file exists - don't save, add to our already exist list
DupList.Add(e.FileName)
Session("DupList") = DupList
Else
' file is ok, new - save it
Dim strFileSave As String
strFileSave = Server.MapPath("~/Content/" & e.FileName)
AjaxFileUpload1.SaveAs(strFileSave)
' now add to database
Dim NewRow As DataRow = rstFiles.NewRow
NewRow("FileName") = e.FileName
NewRow("UpLoadTime") = Date.Now
NewRow("User_id") = 1
NewRow("Size") = e.FileSize
NewRow("SavePath") = Path.GetDirectoryName(strFileSave) ' get path only
rstFiles.Rows.Add(NewRow)
MyRstUpdate(rstFiles, "MyUpLoadFiles")
End If
End Sub
So note in above HOW WE SKIP the file if it exists. And of course if it does exist, then we of course don't make an entry in the MyFilesUpLoad table.
Ok, so all files up-load - that js button click fires, and we now have this final code stub run:
Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click
' this final code is triggered by the javascrpt "click" on
' all file uplaod done
' if there are some duplicates - dispay to user.
If DupList.Count > 0 Then
txtDups.Visible = True
For Each s As String In DupList
If txtDups.Text <> "" Then txtDups.Text &= vbCrLf
txtDups.Text &= s & " already exists - skipped and not uploaded"
Next
End If
' now addtonal code - maybe display gird of up-loaded files
Dim strSQL As String = "select * from MyUpLoadFiles where UpLoadTime >= @D"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("@D", SqlDbType.DateTime).Value = Date.Today
Gfiles.DataSource = MyRstP(cmdSQL)
Gfiles.DataBind()
' hide up-loader
AjaxFileUpload1.Visible = False
End Sub
So, it will look like this:

We hit ok, and now we have/see this:

Ok, so now lets try to re-upload two files that exist.
We So, we will see this:

So, we persist that "bad" list, and skip/don't save the file in the complete event.
And here are the two data helper routines - I don't think it needs much suggesting that one gets VERY tired VERY fast by having to type over and over some simple code to get data into a table - so I used these two helper routines to save World poverty and a few keyboards
Public Function MyRstP(cmdSQL As SqlCommand) As DataTable
Dim rstData As New DataTable
Using cmdSQL
Using conn = New SqlConnection(My.Settings.TEST4)
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Public Sub MyRstUpdate(rst As DataTable, strTable As String)
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand("SELECT * from " & strTable, conn)
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
conn.Open()
da.Update(rst)
End Using
End Using
End Sub
Edit: Check for "confirmed" file
后續問題不僅是檔案是否存在,而且在某些時候(或某些方式 - 尚未披露),用戶可以選擇復選框或更改上傳檔案的狀態。如果檔案還沒有被確認,那么我們仍然允許上傳。
所以,有問題的代碼是這樣的:
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = @F
AND Confirmed = 9"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("@F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then ' 檔案存在。' 檔案已確認 - 不要保存,添加到我們已經存在的串列 DupList.Add(e.FileName) Session("DupList") = DupList Else ' 檔案沒問題,新的 - 保存 - (或未確認)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405799.html
標籤:
上一篇:如何在C#VisualStudio中為單選按鈕創建數字值?
下一篇:在遞回中使用回傳與不回傳?
