Multiple File Uploading using Javascript and Web API

Hi Guys,

I had a requirement to make way to upload multiple files using basic htmls. So I used javascript to achieve this. Hope you like it.





1) MultiFileUpload.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MulitpleFileUpload.aspx.cs" Inherits="MulitpleFileUpload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
     <script>
         function addRow() {
             var table = document.getElementById('myTable');
             var row = table.insertRow(0);
             var cell1 = row.insertCell(0);
             var cell2 = row.insertCell(1);
             var cell3 = row.insertCell(2);
             cell1.setAttribute("class", "formLabelTd");
             cell2.innerHTML = "<input type='File' />";
             cell2.setAttribute("class", "formControlTd");
             cell1.innerHTML = "<input type='text'  />";
         }





         function saveFiles() {

             var data = new FormData();




             var x = document.getElementById("myTable").getElementsByTagName("INPUT");
             var y = [];
             var imageFile;


             if (Validate()) {

                 var id = 1;
                 for (var cnt = 0; cnt < x.length; cnt++) {
                     if (x[cnt].type == "file") {
                         imageFile = x[cnt];
                         data.append("UploadedImage" + id, imageFile.files[0]);
                         id++;
                     }
                     else if (x[cnt].type == "text") {
                         data.append("UploadedText" + id, x[cnt].value);

                     }

                 }
                 


            var xhr = getXMLHttpRequest();
            xhr.open("POST", "/api/FileUpload/UploadFile", true);

            xhr.send(data);
            return true;
        }
        else
            return false;


    }

    function getXMLHttpRequest() {
        if (window.XMLHttpRequest) {
            return new window.XMLHttpRequest;
        }
        else {
            try {
                return new ActiveXObject("MSXML2.XMLHTTP.3.0");
            }
            catch (ex) {
                return null;
            }
        }
    }

    var message = 'File Extension Must be (PDF, DOC, DOCx, JPG, JIF, TIFF)';

    var _validFileExtensions = [".jpg", ".tiff", ".pdf", ".doc", ".docx"];
    function Validate() {
        var arrInputs = document.getElementById("myTable").getElementsByTagName("input");
        for (var i = 0; i < arrInputs.length; i++) {
            var oInput = arrInputs[i];
            if (oInput.type == "file") {
                var sFileName = oInput.value;
                if (sFileName.length > 0) {
                    var blnValid = false;
                    for (var j = 0; j < _validFileExtensions.length; j++) {
                        var sCurExtension = _validFileExtensions[j];
                        if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                            blnValid = true;
                            break;
                        }
                    }

                    if (!blnValid) {
                        document.getElementById("spMore").innerText = message;
                        return false;
                    }
                }
            }
        }
        document.getElementById("spMore").innerText = "";
        return true;
    }



</script>
<body>
    <form id="form1" runat="server">
    <div>
     <form name="formUpload" id="formUpload" enctype="multipart/form-data">
                                <span style="color:red" id="spMore"></span>
                                 <table width="50%" id="myTable">
                                        <td width="20%" class="formLabelTd">
                            <input type="text" />
                                            
                        </td>
                        <td Width="75%" class="formControlTd">
                            <input type="file"  />
                            
                            
                        </td>
                                     <td width="5%">
                                         <img style="float:right" src="Images/Add.png" onclick="addRow()" />
                                     </td>
                                    </table >
                                 
    </form>
        <input type="button" value="Upload Files" onclick="saveFiles()" />
    </div>
    </form>
</body>

</html>

2) FileUploadController.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

public class FileUploadController : ApiController
{
    [HttpPost]
    public void UploadFile()
    {
        try
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                string uploadText;
                int fileSize_AttachedFile;
                byte[] fileContent_AttachedFile;
                File objFile;
                BinaryReader oBinaryReader_AttachedFile;
               
                // Get the uploaded image from the Files collection
                for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                {
                    var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage" + (i + 1)];

                    if (httpPostedFile != null)
                    {
                        uploadText = HttpContext.Current.Request.Form["UploadedText" + (i + 1)];
                        //Save the File
                        using (LocationDataDataContext context = new LocationDataDataContext())
                        {
                            oBinaryReader_AttachedFile = new BinaryReader(httpPostedFile.InputStream);
                            fileSize_AttachedFile = Convert.ToInt32(httpPostedFile.ContentLength);
                            fileContent_AttachedFile = oBinaryReader_AttachedFile.ReadBytes(fileSize_AttachedFile);

                            objFile = new File() { FileBytes = fileContent_AttachedFile,
                                FileName = Path.GetFileName(httpPostedFile.FileName),
                                                        Remarks = uploadText
                            };

                            context.Files.InsertOnSubmit(objFile);
                            context.SubmitChanges();


                        }
                    }


                }


            }
        }
        catch
        {

        }
    }

}






Comments