Aaron Patten Aaron Patten - 2 months ago 8
ASP.NET (C#) Question

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

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<ViewDataUploadFilesResult> 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.

Answer

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)