Valums Ajax文件上传适用于IE,但不适用于Firefox

时间:2012-05-12 11:48:06

标签: c# sql-server ajax asp.net-mvc-3 sql-server-2008

我正在ASP.NET MVC3中开发,我有以下代码用于在Sql Server 2008中保存文件,它适用于IE(我使用的是IE9),但在Firefox中我得到错误“Index is out of of范围。必须是非负数且小于集合的大小。\ r \ n参数名称:index“,我该如何解决这个问题?谢谢

[HttpPost]
    public ActionResult FileUpload(string qqfile)
    {
        try
        {
            HttpPostedFileBase postedFile = Request.Files[0];
            var stream = postedFile.InputStream;
            App_MessageAttachment NewAttachment = new App_MessageAttachment
            {
                FileName = postedFile.FileName.ToString().Substring(postedFile.FileName.ToString().LastIndexOf('\\') + 1),
                FilteContentType = postedFile.ContentType,
                MessageId = 4,
                FileData = new byte[postedFile.ContentLength]
            };
            postedFile.InputStream.Read(NewAttachment.FileData, 0, postedFile.ContentLength);
            db.App_MessageAttachments.InsertOnSubmit(NewAttachment);
            db.SubmitChanges();
        }
        catch (Exception ex)
        {
            return Json(new { success = false, message = ex.Message }, "application/json");
        }
        return Json(new { success = true }, "text/html");
    }

1 个答案:

答案 0 :(得分:2)

Valums Ajax上传有2种模式。如果它识别出浏览器支持HTML5文件API(FireFox无疑就是这种情况),它会使用此API而不是使用enctype="multipart/form-data"请求。因此,在您的控制器操作中,您需要考虑这些差异,对于支持HTML5的现代浏览器,请直接阅读Request.InputStream

[HttpPost]
public ActionResult FileUpload(string qqfile)
{
    try
    {
        var stream = Request.InputStream;
        var filename = Path.GetFileName(qqfile);

        // TODO: not sure about the content type. Check
        // with the documentation how is the content type 
        // for the file transmitted in the case of HTML5 File API
        var contentType = Request.ContentType;
        if (string.IsNullOrEmpty(qqfile))
        {
            // IE
            var postedFile = Request.Files[0];
            stream = postedFile.InputStream;
            filename = Path.GetFileName(postedFile.FileName);
            contentType = postedFile.ContentType;
        }
        var contentLength = stream.Length;

        var newAttachment = new App_MessageAttachment
        {
            FileName = filename,
            FilteContentType = contentType,
            MessageId = 4,
            FileData = new byte[contentLength]
        };
        stream.Read(newAttachment.FileData, 0, contentLength);
        db.App_MessageAttachments.InsertOnSubmit(newAttachment);
        db.SubmitChanges();
    }
    catch (Exception ex)
    {
        return Json(new { success = false, message = ex.Message });
    }
    return Json(new { success = true }, "text/html");
}

代码可能需要一些调整。我现在没有时间对其进行测试,但您明白了:在启用HTML5的浏览器中,文件直接写入请求正文,而对于不支持File API的浏览器,则传输文件数据使用标准multipart/form-data编码。