asp.netsql-serverfile-uploadasp.net-webpagesvarbinarymax

File Upload to Database for ASP.Net Webpages


Im having some trouble finding a way to Upload a document to the database in varbinary(max) with ASP.Net Webpages 2 and I would also like to download it.

So far what i have is this below which supposed to upload a file to a directory on the website but it isn't doing anything. Any help would be great. Thanks

         var fileName = "";
         var fileSavePath = "";
         int numFiles = Request.Files.Count;
         int uploadedCount = 0;
         for (int i = 0; i < numFiles; i++)
         {
             var uploadedFile = Request.Files[i];
             if (uploadedFile.ContentLength > 0)
             {
                 fileName = Path.GetFileName(uploadedFile.FileName);
                 fileSavePath = Server.MapPath("~/UploadedFiles/" +
                   fileName);
                 uploadedFile.SaveAs(fileSavePath);
                 uploadedCount++;
             }
         }
         message = "File upload complete. Total files uploaded: " +
           uploadedCount.ToString();

Solution

  • The following code goes at the top of the page where you have your file upload. Note that you should amend the table and field names according to your database. Also, you should ensure that the form that includes your upload control has the enctype attribute set to multipart/form-data:

    @{ 
        int id = 0;
        var fileName = "";
        var fileMime = "";
        if (IsPost) {
            var uploadedFile = Request.Files[0];
            fileName = Path.GetFileName(uploadedFile.FileName);
            if(fileName != String.Empty)
            {
                fileMime = uploadedFile.ContentType;
                var fileStream = uploadedFile.InputStream;
                var fileLength = uploadedFile.ContentLength;
    
                byte[] fileContent = new byte[fileLength];
                fileStream.Read(fileContent, 0, fileLength);
                var db = Database.Open("FileUploading");
                var sql = "INSERT INTO Files (FileName, FileContent, MimeType) VALUES (@0,@1,@2)";
                db.Execute(sql, fileName, fileContent, fileMime);
            }
        }
    }
    

    To display a file from the database, you need a separate "handler" file that contains just this code:

    @{
        int id = 0;
        if(Request["Id"].IsInt()){
            id = Request["Id"].AsInt();
            var db = Database.Open("FileUploading");
            var sql = "Select * From Files Where FileId = @0";
            var file = db.QuerySingle(sql, id);
            if(file.MimeType.StartsWith("image/")){
                Response.AddHeader("content-disposition", "inline; filename=" + file.FileName);
            } else {
                Response.AddHeader("content-disposition", "attachment; filename=" + file.FileName);
            }
            Response.ContentType = file.MimeType;
            Response.BinaryWrite((byte[])file.FileContent);
        }
    }
    

    This file is used as the src attribute for an image file or as the URL for a link to a file that should be downloaded such as a PDF or Word file. If you call this handler file "download.cshtml", the link for an image file saved in the database should look like this:

    <img src="download.cshtml?Id=@id" alt="" />
    

    where the Id parameter value is the id fo the file in the database. A download link looks like this:

    <a href="download.cshtml?Id=@id">Click Here</a>
    

    All of this has been taken from my article: http://www.mikesdotnetting.com/Article/148/Save-And-Retrieve-Files-From-a-Sql-Server-CE-Database-with-WebMatrix. The only difference between the article which features a SQL Compact database is that the data type for files in SQL CE is image as opposed to varbinary(max) in SQL Server.