Upload files without using ngFileUpload in AngularJS and Web API in ASP.Net

Last Reply 17 hours ago By skp

Posted 11 days ago

How to upload a pdf file into the database using angularjs and web api

I have button called upload files, if I click on that a file explorer window opens I am clicking on any file to upload.

And then, after selecting the file, I am clicking on another button called save which is used to save the file into the database.

My file datatype in database is varbinary(max).

Note : Is there a way to insert pdf file into database without using any of the third party plugins like ngfileupload, etc?

 

Posted 4 days ago Modified on 4 days ago

Hi skp,

If you want to upload without 3rd party libraries use FormData.

This will work on all the latest browsers.

HTML

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', []);
    app.controller('MyController', ['$scope', '$http', function ($scope, $http) {
        $scope.UploadFile = function () {
            var files = document.getElementById("fuFiles").files;
            var formData = new FormData();
            for (var i = 0; i < files.length; i++) {
                formData.append('file' + i, files[i]);
            }
            $http.post("/Home/Upload/", formData, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            }).success(function (r) {
                $scope.Files = r;
            }).error(function (r) {
            });
        };
    } ]);        
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <input id="fuFiles" type="file" multiple="multiple" />
    <button type="button" ng-click="UploadFile()">Upload</button>
    <hr />
    <table border="0" cellpadding="0" cellspacing="0">
        <tr ng-repeat="file in Files">
            <td><img ng-src="{{file}}" style="height: 100px; width: 100px" /><br /><br /></td>
        </tr>
    </table>
</div>

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Upload()
    {
        //Create the Directory.
        string path = Server.MapPath("~/Uploads/");
        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path);
        }

        //Save the Files.
        foreach (string key in Request.Files)
        {
            HttpPostedFileBase postedFile = Request.Files[key];
            // Save in folder.
            postedFile.SaveAs(path + System.IO.Path.GetFileName(postedFile.FileName));

            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(postedFile.InputStream);
            byte[] bytes;
            using (System.IO.BinaryReader br = new System.IO.BinaryReader(postedFile.InputStream))
            {
                bytes = br.ReadBytes(postedFile.ContentLength);
            }
            // Code to save in Database.
            FilesEntities entities = new FilesEntities();
            tblFile file = new tblFile
            {
                Name = System.IO.Path.GetFileName(postedFile.FileName),
                ContentType = postedFile.ContentType,
                Data = bytes
            };
            entities.tblFiles.Add(file);
            entities.SaveChanges();
        }

        List<string> images = new List<string>();
        foreach (string file in System.IO.Directory.GetFiles(path))
        {
            images.Add("Uploads/" + System.IO.Path.GetFileName(file));
        }

        return Json(images);
    }
}

Screenshot

For more details refer below article.

Upload (Insert) and Download (Retrieve) Files from Database using Web API in ASP.Net MVC


Posted 17 hours ago

 

[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