使用。NET MVC3与实体框架在SQL Server数据库中存储文件 [英] Store file in SQL Server database using .Net MVC3 with Entity Framework

查看:124
本文介绍了使用。NET MVC3与实体框架在SQL Server数据库中存储文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要存储和从SQL Server检索文件到/。

I want to store and retrieve a file into/from SQL Server.

我的基础是:

  • 在SQL Server 2008中
  • 在C#.NET MVC3与实体框架。

请帮助我,我要SQL Server和C#文件上使用的数据类型。如果可能的话来存储文件,而无需刷新页面,这将是更接近我的要求。

Please help me out with datatypes that I have to use on SQL Server and C# file. If possible to store file without refreshing the page that would be more closer to my requirement.

感谢。

推荐答案

下面是一些样品codeS)我省略一堆声明,确认,等于是code将不会运行原样,但你应该能够得到的想法。使用Ajax类型请求提交文件的形式,如果你不想刷新页面。

Here's some "sample codes" ;) I omitted bunch of declarations, validation, etc. so the code will not run as is, but you should be able to get the idea. Use ajax type request to submit your file form if you don't want to refresh the page.

// model
public class UploadedImage
{
    public int UploadedImageID { get; set; }
    public string ContentType { get; set; }
    public byte[] File { get; set; }
}

// controller
public ActionResult Create()
{
    HttpPostedFileBase file = Request.Files["ImageFile"];

    if (file.ContentLength != 0)
    {
        UploadedImage img = new UploadedImage();
        img.ContentType = file.ContentType;
        img.File = new byte[file.ContentLength];

        file.InputStream.Read(img.File, 0, file.ContentLength);

        db.UploadedImages.Add(img);
        db.SaveChanges();
    }

    return View();
}

ActionResult Show(int id) 
{
    var image = db.UploadedImages.Find(id);
    if (image != null)
    {
        return File(image.File, image.ContentType, "filename goes here");
    }
}

这篇关于使用。NET MVC3与实体框架在SQL Server数据库中存储文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆