我在保存到数据库时遇到了问题。我上传时继续插入重复数据。我可以知道如何预防吗?我的代码中没有错误。
asp.net
<asp:FileUpload ID="FileUpload" runat="server" AllowMultiple="true" />
vb.net
Try
If Me.FileUpload.PostedFile.FileName = "" Then
Throw New Exception("Please Attach file!")
Else
For Each postedfile As HttpPostedFile In FileUpload.PostedFiles
fileName = Me.lblId2.Text & "_" & Path.GetFileName(FileUpload.PostedFile.FileName)
FileUpload.PostedFile.SaveAs((Server.MapPath("~/Attachment/UploadFile_/") + fileName))
FilePath = "~/Attachment/UploadFile_/" + fileName
filesize = Convert.ToInt32(fileName.Length)
params.Clear()
strsql = " INSERT INTO tb_upload " & _
" (UploadDT, cr_runnum,DestFileName,DataSize, FileName, Remarks) VALUES " & _
" (@UploadDT, @cr_runnum, @DestFileName, @DataSize, @FileName, @Remarks)"
params.Add("@UploadDT", Format(datetimenow, "dd MMM yyyy hh:mm:ss tt"))
params.Add("@cr_runnum", Me.lblId2.Text.Trim)
params.Add("@DestFileName", FilePath)
params.Add("@DataSize", filesize)
params.Add("@FileName", fileName)
params.Add("@Remarks", Me.txtRemarks.Text)
iResult = Common.execNonQuery(strsql, Common.txn, params)
If iResult = 0 Then
Throw New Exception("Data insertion failed. Please contact MIS Administrator!")
End If
Next
lblUnsuccess.Text = String.Format("{0} files have been uploaded successfully.", FileUpload.PostedFiles.Count)
End If
Catch ex As Exception
Me.lblUnsuccess.Text = ex.Message
Finally
Common.CloseConn()
End Try
函数exec非查询 refer here exec non query
答案 0 :(得分:0)
问题在于您使用的是publishFile作为循环变量,但每次循环时,您使用的是FileUpload.PostedFile
而不是postedFile
。 FileUpload.PostedFile是一种快捷方式,它为您提供了PostedFiles的第一个元素。
此外,正如注释中提到的user7452368,fileName.Length是fileName字符串的长度,而不是文件的大小。这是somebody else's question about how to get the file size。