测试最大文件大小

时间:2015-05-22 18:21:11

标签: asp.net vb.net forms file-upload

 Protected Sub AddFileButton_Click(ByVal sender As Object, _
      ByVal e As System.EventArgs)

        If FileUploader.HasFile Then

            Dim fileSize = FileUploader.PostedFile.ContentLength

            If fileSize > 1048576 Then
                Info.Text = "This file exceeds the allowed file size (1 MB). Please resize the image or select another file."
                Return

            ElseIf fileSize < 1 Then
                Info.Text = "This file does not have enough content to send. Please choose another file."
                Return

            Try
                Dim extension = System.IO.Path.GetExtension(FileUploader.FileName)
                Dim uniqueFileName = System.Guid.NewGuid.ToString() & extension
                FileUploader.SaveAs("\\filepath\" & FileUploader.FileName)
            Catch ex As Exception
                Info.Text = "ERROR: " & ex.Message.ToString()
            End Try
           End If
        End If
    End Sub

由于某些原因,它没有达到If fileSize > 1048576 ThenElse If fileSize < 1 Then。如果它超过我在web.config中定义的1mb限制,它只是执行Try and Catch并显示错误。

我没有看到语法或逻辑错误吗?

1 个答案:

答案 0 :(得分:1)

Check file size before upload

客户端上传取消

在现代浏览器上(FF&gt; = 3.6,Chrome&gt; = 19.0,Opera&gt; = 12.0,以及Safari上的bug),您可以使用HTML5文件API。当文件输入的值发生更改时,此API将允许您检查文件大小是否符合您的要求。当然,这个以及MAX_FILE_SIZE都可以被篡改,所以总是使用服务器端验证。

          document.forms [0] .addEventListener('submit',function(evt){     var file = document.getElementById('file')。files [0];     if(file&amp;&amp; file.size