[Route("api/pdf/InsertFiles")]
[HttpPost]
public HttpResponseMessage InsertFiles()
{
//Read the File from Request.Files collection.
HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];
//Convert the File to Byte Array.
BinaryReader br = new BinaryReader(postedFile.InputStream);
byte[] bytes = br.ReadBytes(postedFile.ContentLength);
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "INSERT_PDF";
sqlCmd.Connection = myConnection;
//sqlCmd.Parameters.Add("@DOCUMENT", SqlDbType.VarBinary).Value = bytes;
sqlCmd.Parameters.AddWithValue("@DOCUMENT", bytes);
myConnection.Open();
sqlCmd.ExecuteNonQuery();
myConnection.Close();
//Send the Base64 string to the Client.
return Request.CreateResponse(HttpStatusCode.OK, Convert.ToBase64String(bytes, 0, bytes.Length));
}
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window, $sce) {
$scope.Base64 = null;
var fileProgress = document.getElementById("fileProgress");
var message = document.getElementById("lblMessage");
$scope.UploadFile = function () {
fileProgress.style.display = "block";
var formData = new FormData();
formData.append(file, document.getElementById("file").files[0]);
var post = $http({
method: "POST",
url: "http://localhost:57566/api/pdf/InsertFiles",
data: formData,
transformRequest: angular.identity,
headers: { 'Content-Type': undefined },
uploadEventHandlers: {
progress: function (e) {
if (e.lengthComputable) {
fileProgress.setAttribute("value", e.loaded);
fileProgress.setAttribute("max", e.total);
}
}
}
});
post.then(function (data, status) {
debugger;
alert('success!');
});
};
});
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
<script src="../Scripts/MyController.js"></script>
</head>
<body>
<div ng-app="MyApp" ng-controller="MyController">
<input id="file" type="file" />
<input type="button" value="Upload" ng-click="UploadFile()" />
<progress id="fileProgress" style="display: none"></progress>
<hr />
</div>
</body>
</html>
ALTER PROCEDURE [dbo].[INSERT_PDF]
@DOCUMENT varbinary(MAX) = NULL
AS
BEGIN
INSERT INTO PDF
(Document)
VALUES
(@DOCUMENT)
END