locked
Upload Multiple Files Asynchronously Using AJAX into SQL Server Database RRS feed

  • Question

  • User-188771657 posted

    Am trying to upload multiple file to database, but getting error

    This is my .aspx file

    <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
        CodeBehind="Default.aspx.cs" Inherits="AJAXFileUploadSQL._Default" %>
    
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
    <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
        <style>
            .ajax__fileupload_button
            {
                background-color: blue;
            }
        </style>
        <script type="text/javascript">
            function onClientUploadComplete(sender, e) {
                var id = e.get_fileId();
                onImageValidated("TRUE", e);
            }
    
            function onImageValidated(arg, context) {
    
                var test = document.getElementById("testuploaded");
                test.style.display = 'block';
    
                var fileList = document.getElementById("fileList");
                var item = document.createElement('div');
                item.style.padding = '4px';
    
                if (arg == "TRUE") {
                    var url = context.get_postedUrl();
                    url = url.replace('&amp;', '&');
                    item.appendChild(createThumbnail(context, url));
                } else {
                    item.appendChild(createFileInfo(context));
                }
    
                fileList.appendChild(item);
    
            }
    
            function createFileInfo(e) {
                var holder = document.createElement('div');
                holder.appendChild(document.createTextNode(e.get_fileName() + ' with size ' + e.get_fileSize() + ' bytes'));
    
                return holder;
            }
    
            function createThumbnail(e, url) {
                var holder = document.createElement('div');
                var img = document.createElement("img");
                img.style.width = '80px';
                img.style.height = '80px';
                img.setAttribute("src", url);
    
                holder.appendChild(createFileInfo(e));
                holder.appendChild(img);
    
                return holder;
            }
        </script>
    </asp:Content>
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        <h2>
            Upload Files Asynchronously Using AJAX into SQL Server Database
        </h2>
        <br />
        <ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
        <div>
            <asp:Label runat="server" ID="myThrobber" Style="display: none;"><img align="absmiddle" alt="" src="uploading.gif"/></asp:Label>
            <ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" padding-bottom="4"
                padding-left="2" padding-right="1" padding-top="4" ThrobberID="myThrobber" OnClientUploadComplete="onClientUploadComplete"
                OnUploadComplete="AjaxFileUpload1_OnUploadComplete" />
            <br />
            <div id="testuploaded" style="display: none; padding: 4px; border: gray 1px solid;">
                <h4>
                    Uploaded files:</h4>
                <hr />
                <div id="fileList">
                </div>
            </div>
        </div>
    </asp:Content>
    

    My CS File

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using System.Collections.Specialized;
    using System.Text;
    using System.IO;
    using System.Linq;
    using AjaxControlToolkit;
    
    namespace AJAXFileUploadSQL
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                String strConnString = ConfigurationManager.ConnectionStrings["Con"].ConnectionString;
                SqlConnection _con = new SqlConnection(strConnString);
    
                if (Request.QueryString["preview"] == "1" && !string.IsNullOrEmpty(Request.QueryString["fileId"]))
                {
                    var fileId = Request.QueryString["fileId"];
                    var fileContentType = (string)Session["fileContentType_" + fileId];
                    var fileName = (string)Session["fileName_" + fileId];
                    byte[] imageBytes = File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("~") + "file.png");
                    var fileContents = imageBytes;
    
                    string ct = (string)Session["fileContentType_" + fileId];
                    if (ct.Contains("jpg") || ct.Contains("gif") || ct.Contains("png") || ct.Contains("jpeg"))
                        fileContents = (byte[])Session["fileContents_" + fileId];
    
                    //using (SqlConnection _con = new SqlConnection("Data Source=ASHRAF-PC;database=AJAXFileUploadSQL;User Id=sa;Password=sa@1;MultipleActiveResultSets=True"))
                     
                 
    
                    using (SqlCommand _cmd = new SqlCommand("UploadFile", _con))
                    {
                        _cmd.CommandType = CommandType.StoredProcedure;
                        _cmd.Parameters.AddWithValue("@FileName", fileName);
                        _cmd.Parameters.AddWithValue("@FileType", fileContentType);
                        _cmd.Parameters.AddWithValue("@FileContent", (byte[])Session["fileContents_" + fileId]);
    
                        _con.Open();
                        _cmd.ExecuteNonQuery();
                        _con.Close();
                    }
    
                    Response.Clear();
                    Response.ContentType = fileContentType;
                    Response.BinaryWrite(fileContents);
                    Response.End();
                }
            }
    
            public byte[] imageToByteArray(System.Drawing.Image imageIn)
            {
                MemoryStream ms = new MemoryStream();
                imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                return ms.ToArray();
            }
    
            protected void AjaxFileUpload1_OnUploadComplete(object sender, AjaxFileUploadEventArgs file)
            {
                Session["fileContentType_" + file.FileId] = file.ContentType;
                Session["fileContents_" + file.FileId] = file.GetContents();
    
                Session["fileName_" + file.FileId] = file.FileName.Split('\\').Last();
    
                file.PostedUrl = string.Format("?preview=1&fileId={0}", file.FileId);
            }
        }
    }
    

    Don't know where is the error

    Friday, December 23, 2016 5:46 AM

Answers