使用ASP上传文件到SQL Server.asp.net MVC 3

本文关键字:asp Server net MVC SQL ASP 文件 使用 | 更新日期: 2023-09-27 18:10:57

我目前正在为客户端开发一个应用程序,该应用程序将使用管理面板将图像上传到图片库,并将一些其他扫描文档上传到数据库。我已经成功地编写了用于保存和检索保存在数据库中的文件的控制器动作。

现在我卡住了如何显示进度条时,文件上传到数据库。我尝试过几个控件,比如jQuery的uploadify和其他一些控件。他们都成功地将文件保存到文件夹中,尽管不是在上传到MS-SQL数据库时。

这是我的模型的一个示例:

    public Class myImages
    {
       [Key, Required]
       public string ImageID { get; set; }
       [Required, MaxLength(100), DisplayName("Image Title:")]
       public string ImageTitle { get; set; }
       [DisplayName("Image File:")]
       public byte[] ImageData { get; set; }
       public string ImageContentType { get; set; }
    }

我在基础设施中创建了一个函数,用于返回上传文件的字节数组,代码如下:

    public byte[] uploadedFileToByteArray(HttpPostedFileBase file)
    {
       int nFileLen = file.ContentLength;
       byte[] result = new byte[nFileLen];
       file.InputStream.Read(result, 0, nFileLen);
       return result;
    }

…这里是Create

的Control Action
    [HttpPost, ValidateInput(false), ValidateAntiForgeryToken]
    public ActionResult Create(myImage myimage)
    {
       if (ModelState.IsValid)
          {
             myimage.ImageID = DateTime.Now.Ticks.ToString();
             myimage.ImageData = uploadedFileToByteArray(Request.Files[0]);
             myimage.ImageContentType = Request.Files[0].ContentType;
             db.Pictures.Add(picture);
             db.SaveChanges();
             return RedirectToAction("Index");  
          }
      return View(picture);
    }

正如我所说的,上面的代码工作得很好,唉,当文件上传时,我似乎无法让进度条工作。有什么办法吗?

我也试过将文件上传到临时文件夹,然后读取该文件的字节,然后上传到SQL Server,这种方法有效,但由于某种原因,我的客户端不希望这样,我也不满意这个解决方案。

我也注意到,当上传文件时,谷歌的chrome浏览器显示上传百分比,如果浏览器可以在客户端访问数据,是否有办法通过jQuery或Ajax访问上传/发送的字节,以在上传时显示进度条?

我使用的是Visual Studio 2010, ASP。. Net, MVC 3。

使用ASP上传文件到SQL Server.asp.net MVC 3

您需要以块的形式将字节读取到内存中,更新在某些服务器端变量中读取的数据量(可能是在会话中),这些变量可以被您用来测量进度的上传插件访问。因为它是你一次读取所有的数据,没有办法报告部分进度。使用另一个操作来报告到目前为止为进度指示器读取的数量。注意,您可能需要使用异步控制器来实现此工作。

注意这只是一个想法。它将需要相当多的工作来实现健壮,处理多个文件等。

public byte[] uploadedFileToByteArray(HttpPostedFileBase file)
{
   int nFileLen = file.ContentLength;
   int currentPosition = 0;
   byte[] result = new byte[nFileLen];
   Session["fileLen"] = nFileLen;
   int bytesRead = file.InputStream.Read(result,0,1000);
   while (bytesRead > 0)
   {
      currentPosition += bytesRead;
      Session["progress"] = currentPosition;
      bytesRead = file.InputStream.Read(result,currentPosition,1000);
   }
   return result;
}
public ActionResult ReportProgress()
{
     int nFileLen = (int)Session["fileLen"];
     int progress = (int)Session["progress"];
     return Json( new { Progress = (float)progress/nFileLen, Complete = nFileLen >= progress } );
}