This is a migrated thread and some comments may be shown as answers.

MSSQL Documents Uploads

2 Answers 129 Views
AsyncUpload
This is a migrated thread and some comments may be shown as answers.
Paolo
Top achievements
Rank 1
Paolo asked on 21 Dec 2011, 02:37 PM
Good Morning,
 I'm new to use a Telerik components and obviously I've have a problem.... :-D. So, the my problem is how to upload Documents (like DOC, Word, Excell ecc ecc) into a MS SQL Server with RadAsynUpload or RadUpload. In this moment I use FileUpload (MS VisualStudio 2010 Component) to uploading a documents, and this working fine but i would like use RadComponent to do this. So the VB code that I use is :

-- Upload  --
Private Function uploadDoc(ByVal oFileUpload As FileUpload) As Boolean

        Dim blnRet As Boolean = False
        Dim oBinaryReader As New IO.BinaryReader(oFileUpload.PostedFile.InputStream)
        Dim oByteArray As Byte() = oBinaryReader.ReadBytes(CInt(oFileUpload.PostedFile.ContentLength))

        oBinaryReader.Close()

        Dim nTkt As String = lbl_NumProt.Text
        Dim TKTdb As New TKTdbDataContext
        Dim oRequest = (From tbl In TKTdb.T_PROTO_INs Where (tbl.Num_Prot = nTkt) Select tbl).First

        oRequest.AttachFilename = oFileUpload.FileName
        oRequest.AttachContentType = oFileUpload.PostedFile.ContentType
        oRequest.AttachFileSize = oByteArray.Length
        oRequest.AttachData = oByteArray

        Try
            TKTdb.SubmitChanges()
            blnRet = True
        Catch ex As Exception
            Throw New System.Exception(ex.Message)
        End Try
        Return blnRet

    End Function

-- Download --
Shared Sub getOwnerAttachDoc(ByVal nTkt As String)

        Dim blnRet As Boolean = False
        Dim TKTdb As New TKTdbDataContext
        Dim oRequest = (From tbl In TKTdb.T_PROTO_INs Where (tbl.Num_Prot = nTkt) Select tbl.AttachContentType, tbl.AttachData, tbl.AttachFilename, tbl.AttachFileSize).First

        Dim Filename As String = HttpContext.Current.Server.UrlEncode(oRequest.AttachFilename)
        Dim ContenType As String = oRequest.AttachContentType
        Dim FileSize As String = oRequest.AttachFileSize

        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.ContentType = "application/octet-stream"
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" & Filename & "")
        HttpContext.Current.Response.AppendHeader("Content-Lenght", FileSize)
        HttpContext.Current.Response.BinaryWrite(oRequest.AttachData.ToArray)
        HttpContext.Current.Response.Flush()
        HttpContext.Current.Response.End()

    End Sub

Is possible to migrate that VB Code if I want use RadUploadControl or RadAsyncControl?

Thanks
Paolo

2 Answers, 1 is accepted

Sort by
0
Richard
Top achievements
Rank 1
answered on 22 Dec 2011, 06:54 PM
Paolo:

You can use RadUpload to save your files directly into a SQL Server Database, instead of to a file system.

Here are a couple of forum threads that will help you do this.

Upload file to database instead of save to folder


Saving to database using radupload

Take a look at the Upload/Manipulate Uploaded Files online demo which you can use as the starting point. Also, the Grid/Binary Images and Upload in Grid uses a RadUpload from with the RadGrid to save images directly into a database. This should help.

Cheers!
0
Richard
Top achievements
Rank 1
answered on 23 Dec 2011, 11:00 PM
I'm posting a simple demo that uses the ASP.NET AJAX RadUpload control to add a new row in the SQL Server Northwind database "Employees" table with the fields: "LastName, FirstName, Photo". The photo is added as a SqlDbType.Image.

The simple form is attached as a screen capture.

Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
    <title></title>
    <telerik:RadStyleSheetManager id="RadStyleSheetManager1" runat="server" />
    <style id="Style1" type="text/css" runat="server">
        .radupload
        {
            float: left;
            margin-bottom: 20px;
        }
        .bigModule
        {
            clear: both;
        }
        .smallModule
        {
            margin-bottom: 20px;
        }
        #controlContainer
        {
            vertical-align: top;
            padding: 20px 10px;
        }
        .ruProgressArea
        {
            position: absolute;
            top: 0;
            left: 10px;
        }
        input.RadUploadSubmit
        {
            margin-top: 20px;
        }
         
        .rc3
        {
            padding-left: 40px !important;
        }
        .rc3 .title
        {
            margin-left: -20px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
        <scripts>
            <%--Needed for JavaScript IntelliSense in VS2010--%>
            <%--For VS2008 replace RadScriptManager with ScriptManager--%>
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
        </scripts>
    </telerik:RadScriptManager>
    <telerik:RadProgressManager id="Radprogressmanager1" runat="server" />
    <telerik:RadInputManager ID="RadInputManager1" runat="server">
        <telerik:TextBoxSetting BehaviorID="TextBoxSetting" EmptyMessage="-Enter Name-"
            SelectionOnFocus="SelectAll">
            <PasswordStrengthSettings IndicatorWidth="100px" />
            <TargetControls>
                <telerik:TargetInput ControlID="ExtendedTextBox1" />
                <telerik:TargetInput ControlID="ExtendedTextBox2" />
            </TargetControls>
        </telerik:TextBoxSetting>
    </telerik:RadInputManager>
    <div style="position: relative;">
        <table>
            <tr>
                <td><asp:Label ID="lblFirstName" Text="First Name: " runat="server"></asp:Label><asp:textbox ID="ExtendedTextBox1" runat="server"></asp:textbox></td>           
            </tr>
            <tr>
                <td><asp:Label ID="lblLastName" Text="Last Name: " runat="server"></asp:Label><asp:textbox ID="ExtendedTextBox2" runat="server"></asp:textbox></td>
            </tr>
            <tr>
                <td id="controlContainer">
                    <telerik:RadUpload ID="RadUpload1" runat="server" InitialFileInputsCount="1" MaxFileInputsCount="1"
                        AllowedFileExtensions=".jpg,.jpeg,.png" >
                </telerik:RadUpload>
                         
                      
                    <telerik:RadProgressArea id="progressArea1" runat="server" />
                    <asp:Button ID="buttonSubmit" runat="server" CssClass="RadUploadSubmit" OnClick="buttonSubmit_Click"
                        Text="Submit" Style="margin-top: 6px" />
                </td>
                <td>
                    <div class="smallModule">
                        <div class="rc1">
                            <div class="rc2">
                                <div class="rc3" style="width: 240px">
                                    <div class="title" style="color: green">
                                        Uploaded valid files (*.jpg, *.jpeg):</div>
                                    <asp:Label ID="labelNoResults" runat="server" Visible="True">No uploaded files</asp:Label>
                                    <asp:Repeater ID="repeaterValidResults" runat="server" Visible="False">
                                        <ItemTemplate>
                                            <%#DataBinder.Eval(Container.DataItem, "FileName")%>
                                            (<%#DataBinder.Eval(Container.DataItem, "ContentLength").ToString() + " bytes"%>)<br />
                                            <br />
                                        </ItemTemplate>
                                    </asp:Repeater>
                                    <div class="title" style="color: red; padding-top: 40px;">
                                        Invalid files:</div>
                                    <asp:Label ID="labelNoInvalidResults" runat="server" Visible="True">No invalid files</asp:Label>
                                    <asp:Repeater ID="repeaterInvalidResults" runat="server" Visible="False">
                                        <ItemTemplate>
                                            File:
                                            <%#DataBinder.Eval(Container.DataItem, "FileName") %>
                                            (<%#DataBinder.Eval(Container.DataItem, "ContentLength").ToString() + " bytes"%>)
                                            <br />
                                            Mime-type:
                                            <%#DataBinder.Eval(Container.DataItem, "ContentType").ToString()%>
                                        </ItemTemplate>
                                    </asp:Repeater>
                                </div>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
 
Default.aspx.cs:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
 
public partial class Default : System.Web.UI.Page
{
    string ConnectionString = @"Data Source=zaslaw\sqlexpress;Initial Catalog=Northwind;Integrated Security=True";
 
    protected void Page_Load(object sender, System.EventArgs e)
    {
        RadUpload1.ControlObjectsVisibility = ControlObjectsVisibility.None;
    }
 
    protected void buttonSubmit_Click(object sender, System.EventArgs e)
    {
        BindValidResults();
        BindInvalidResults();
    }
 
    private void BindValidResults()
    {
        if (RadUpload1.UploadedFiles.Count > 0)
        {
            UploadedFile validFile = RadUpload1.UploadedFiles[0];
            /*Comment these lines out to avoid saving files to the folder system*/
            //string targetFolder = Server.MapPath("~/MyFiles");
            //validFile.SaveAs(Path.Combine(targetFolder, validFile.GetName()), true);           
 
            byte[] fileData = new byte[validFile.InputStream.Length];
            validFile.InputStream.Read(fileData, 0, (int)validFile.InputStream.Length);
 
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO [Employees] ([LastName], [FirstName], [Photo]) VALUES (@LastName, @FirstName, @Photo)", conn);
 
                cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 50, "LastName");
                cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 4000, "FirstName");
                cmd.Parameters.Add("@Photo", SqlDbType.Image);
 
                cmd.Parameters["@LastName"].Value = ExtendedTextBox2.Text;
                cmd.Parameters["@FirstName"].Value = ExtendedTextBox1.Text;
                cmd.Parameters["@Photo"].Value = fileData;
 
                cmd.ExecuteScalar();
            }
                    labelNoResults.Visible = false;
        repeaterValidResults.Visible = true;
        repeaterValidResults.DataSource = RadUpload1.UploadedFiles;
        repeaterValidResults.DataBind();
        }
        else
        {
        labelNoResults.Visible = true;
        repeaterValidResults.Visible = false;
        }
}
 
    private void BindInvalidResults()
    {
        if (RadUpload1.InvalidFiles.Count > 0)
        {
            labelNoInvalidResults.Visible = false;
            repeaterInvalidResults.Visible = true;
            repeaterInvalidResults.DataSource = RadUpload1.InvalidFiles;
            repeaterInvalidResults.DataBind();
        }
        else
        {
            labelNoInvalidResults.Visible = true;
            repeaterInvalidResults.Visible = false;
        }
    }
}

Hope this helps.

Cheers!
Tags
AsyncUpload
Asked by
Paolo
Top achievements
Rank 1
Answers by
Richard
Top achievements
Rank 1
Share this question
or