0

我正在尝试创建一个上传页面,在其中上传 .swf 文件,然后将文件名添加到我的数据库中。以前我已经能够做到这一点,但是,现在它似乎给了我错误“索引超出范围。必须是非负数并且小于集合的大小。参数名称:索引”我的代码如下:

@{
Page.Title = "Add Game";

//Variables
var GameName = "";
var Tags = "";
var Gamefile = "";

//Required fields
Validation.RequireField("Name", "Please give the game a name.");
Validation.RequireField("file", "Please upload a file.");
//Maximum name length
Validation.Add("Name",
    Validator.StringLength(
        maxLength: 100,
        errorMessage: "Name must be less than 100 characters")
        );
//SWF file validation
Validation.Add("file",
    Validator.Regex(@"^.*\.(swf|SWF)$", "Invalid filetype, you must upload a .swf flash file")
    );

    if (IsPost && Validation.IsValid()) {
    var db = Database.Open("Surgestuff");
    var gCat = "";
    var fileData = Request.Files[0];
    var fileName = Guid.NewGuid().ToString() + ".swf";
    var fileSavePath = Server.MapPath("~/upload/" + fileName);
    var AddBy = WebSecurity.CurrentUserName;
    gCat=Request["formCat"];
    Gamefile = fileName;
    fileData.SaveAs(fileSavePath);
    var SQLINSERT = "INSERT INTO Games (Name, file_path, Category, AddBy) " + "VALUES (@0, @1, @2, @3)";
    db.Execute(SQLINSERT, GameName, Gamefile, gCat, AddBy);
    Response.Redirect("~/Games");

    }
}

出于某种原因,即使我提交了文件,

var fileData = Request.Files[0];给我那个错误

4

1 回答 1

2

Web Pages 2 验证帮助程序不能与input type="file". 它们仅适用于集合中包含的元素Request.Form。文件上传出现在Request.Files集合中。

您可以采用几种方法来验证文件上传。您可以使用模型状态:

if(IsPost && Request.Files[0].ContentLength == 0){
    ModelState.AddError("file", "You must choose a file");
}

if (IsPost && Validation.IsValid() && ModelState.IsValid) {
    // etc 

Or you can add a hidden field, and when the form is submitted, populate its value with that of the file upload via JavaScript. Then you can use the new Validation helpers as you are currently trying to do, but on the hidden field instead.

于 2012-11-28T17:25:28.107 回答