开发者

LINQ doesn't provide a byte[] data type for storing files

开发者 https://www.devze.com 2023-04-12 09:08 出处:网络
I\'m trying to store a file in an SQL Server database and am using ASP.NET MVC 3 with LINQ to SQL in C#. When I try to set the data type of a column to byte[] it says that this is an in

I'm trying to store a file in an SQL Server database and am using ASP.NET MVC 3 with LINQ to SQL in C#. When I try to set the data type of a column to byte[] it says that this is an invalid data type. Using the vrabinary(MAX) data type instead seems like the logical thing to do.

The goal is to store PDF files in a database that the user has elected to upload using an HTTP file uploader. The error occurs during assignment of the LINQ member variable that refers to the column where the file is to be stored.

Error 3 Cannot implicitly convert type 'System.Web.HttpPostedFileBase' to 'System.Data.Linq.Binary' C:\Users\Aaron Patten\Documents\Visual Studio 2010\Projects\MyApp\MyApp\Controllers\MyController.cs 66 31 MyApp

I haven't found much in the way of other people encountering this problem, so I think there must be something I'm missing that is too elementary for anyone to post.

My controller:

    public ActionResult UploadPDF()
    {
        List<ViewDataUploadFilesR开发者_Go百科esult> r = new List<ViewDataUploadFilesResult>();

        HttpPostedFileBase hpf;// = Request.Files[file] as HttpPostedFileBase;

        foreach (string file in Request.Files)
        {
            hpf = Request.Files[file] as HttpPostedFileBase;
            if (hpf.ContentLength == 0)
                continue;
            string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images\\" + Path.GetFileName(hpf.FileName));
            hpf.SaveAs(savedFileName);

            r.Add(new ViewDataUploadFilesResult()
            {
                Name = savedFileName,
                Length = hpf.ContentLength
            });
        }

        MyApp.Models.MyAppDataContext db = new MyApp.Models.MyAppDataContext();

        MyApp.Models.PDFFile myPDFFile = new MyApp.Models.PDFFile();

        myPDFFile.Content = hpf;
        db.questions.InsertOnSubmit(myPDFFile);
        db.SubmitChanges();

        return View("UploadPDF", r);
    }

What's the proper way of going about all this?

P.S.: How do I display the PDF as an embedded object without saving it to the server?

D.A.P.


The error message tells you what's wrong... you are setting Content=hpf. hpf is a HttpPostedFileBase so it first needs to be converted to a byte[]. Do that by reading the byte[] out of the hpf's stream.

myPDFFile.Content = new BinaryReader(hpf.InputStream).ReadBytes(hpf.InputStream.Length)


In your LINQ to SQL entity designer change the field giving you trouble from System.Data.Linq.Binary to a type of System.Byte[]. The conversion will be implicit upon submission.

LINQ doesn't provide a byte[] data type for storing files

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号