0

我有一个在 asp.net 4.0 中使用 FileUpload 控件的文件上传表单。在我的上传按钮上,我检查正在提交的文件是否存在一些限制,例如:

FileUpload fu = new FileUpload();

    if (fu.HasFile)
    {
        if ((extension == ".jpg") || (extension == ".png") || (extension == ".gif"))
        {
             if (fu.PostedFile.ContentLength <= 2MB)
             {
                 fu.SaveAs("path"); // save the file on the server
                 // check file header ...       
             }
         }
    }

问题是,当我提交视频(显然具有不同的扩展名和大小> 2MB)而不是在客户端上检查并给出我设置的错误时,它会上传它然后客户端收到错误。问题是如果客户端提交一个 1GB 的文件怎么办?!我的意思是,它如何从扩展和大小验证传递到 SaveAs(),我无法理解。有什么意见吗?谢谢!

4

3 回答 3

2

Unfortunately, that code runs on the server, which means it can only do those checks after the file has been uploaded.

If the user attempts to upload a very large file, the request length limits (defined in web.config) will catch it, and the upload will be aborted once the limit is reached.

Other than that, you really do have to check the file on the server; and you should check more than just the extension. Someone could easily change the extension of a file to something else. That may or may not be an actual problem - but most likely is! (if nothing else, subsequent website users would see broken image placeholders when the browser tries to load a Word document as if it were an image, for example)

于 2013-03-01T11:33:11.330 回答
0

如果您使用的是 html5,那么您可以使用 FileReader。 文件阅读器 Javascript

  1. 您可以从客户端验证大小、内容类型。
  2. 一旦通过验证,您可以将其发布到服务器。

代码取自:FileReader Javascript

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
      output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                  f.size, ' bytes, last modified: ',
                  f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                  '</li>');
    }
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

文件阅读器的 polyfills

  1. 文件阅读器 polyfill
  2. 浏览器支持。
于 2013-03-01T11:36:15.137 回答
0

这是您的实际代码吗?什么是 2MB?它不是字符串或整数。我很惊讶它甚至编译。你应该有这样的东西:

 int iFileSize = file.ContentLength;


    if (iFileSize > 1000000)  // 1MB approx (actually less though)
    {
        // File is too big so do something here
        return;
    }
于 2013-03-01T11:36:28.433 回答