Insert pdf file as varbinary(max) into the database using web API in Angularjs?

All we need is an easy explanation of the problem, so here it is.

I have tried inserting pdf file into the database, but it is getting inserted as 0 for int datatype and null for varbinary(max) into the database. I have also tested using postman, by passing the data into web API controller, but still it is getting inserted as 0 and null into the database.

        public int insertReceiptDocument(receiptDocument rd)
            rd = new receiptDocument();            
            SqlConnection myConnection = new SqlConnection();
            myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["ERPConnectionString"].ConnectionString;
            SqlCommand sqlCmd = new SqlCommand();
            //DateTime now = DateTime.Now;
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.CommandText = "INSERT_RECEIPT_DOCUMENT";
            sqlCmd.Connection = myConnection;
            sqlCmd.Parameters.AddWithValue("@RDID", rd.RDID);
            sqlCmd.Parameters.AddWithValue("@RECEIPTID", rd.RECEIPTID);
            //var request = HttpContext.Current.Request;
            //var filePath = "Z:\\Templates\\Images\\" + request.Headers["filename"];
            //using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
            //    request.InputStream.CopyTo(fs);
            sqlCmd.Parameters.AddWithValue("@DOCUMENT", rd.DOCUMENT);
            int rowInserted = sqlCmd.ExecuteNonQuery();
            return 1;
$scope.submit = function (files) {
    //var fd = new FormData();
    //Take the first selected file
    //fd.append("payloadFile", 33);
    //fd.append("payloadFile", 98746);
    //fd.append("payloadFile", files);

               fd, { headers: { 'Content-Type': undefined } }
    ).then(function (response) {
<form name="oForm" id="oForm">
    File: <input type="file" id="payloadFile" name="payloadFile" /><br />
    <input type="submit" value="Submit"  ng-click="submit(files)" />
public class receiptDocument
        public int RDID { set; get; }
        public int RECEIPTID { set; get; }
        public byte[] DOCUMENT { set; get; }

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Instead of

sqlCmd.Parameters.Add("@DOCUMENT", rd.DOCUMENT);

you can write

sqlCmd.Parameters.Add("@DOCUMENT", SqlDbType.VarBinary, rd.DOCUMENT.Length).Value = rd.DOCUMENT;

also cross check whether you are getting correct value in rd.DOCUMENT

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply