ASP.NET - How to upload a file using RadAsyncUpload control

Asked By Vidyasagar Patil on 05-May-11 08:47 AM

  Hi how to upoad a file  using RadAsyncUpload control  in the database

  I have used the following code  BUT ITS GIVING ME AN ERROR  WHICH SAYS  NO ROW AT POSITION 0

  The code is as follows

  

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Telerik.Web.UI;

using System.Data;

using System.Data.SqlClient;

using System.Data.OleDb;

using System.Xml;

using System.Text;

using System.Xml.XPath;

using System.Runtime.Serialization.Formatters.Binary;

using System.Configuration;

using System.IO;

using System.Drawing;

using System.Drawing.Imaging;

 

namespace WebApplication2

{

public partial class practiceupload : System.Web.UI.Page

{

static string sheetname;

protected void Page_Load(object sender, EventArgs e)

{


}

private List<Telerik.Web.UI.UploadedFileInfo> uploadedFiles = new List<Telerik.Web.UI.UploadedFileInfo>();

public List<Telerik.Web.UI.UploadedFileInfo> UploadedFiles

{

get { return uploadedFiles; }

set { uploadedFiles = value; }

}

private void PopulateUploadedFilesList()

{

foreach (UploadedFile file in RadAsyncUpload1.UploadedFiles)

{

UploadedFileInfo uploadedFileInfo = new UploadedFileInfo(file);

UploadedFiles.Add(uploadedFileInfo);


}

}

 

 

protected void Upload_Click(object sender, EventArgs e)

{

PopulateUploadedFilesList();


// UploadedFileInfo uploadedFileInfo = new UploadedFileInfo();

//string fna=uploadedFileInfo.FileName;

//string filename = RadAsyncUpload1.UploadedFiles.ToString();

foreach (UploadedFile file in RadAsyncUpload1.UploadedFiles)

{

UploadedFileInfo uploadedFileInfo = new UploadedFileInfo(file);

UploadedFiles.Add(uploadedFileInfo);

string fna = uploadedFileInfo.FileName;

 

string connectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fna + "; Extended Properties=Excel 8.0;";

OleDbConnection ad = new OleDbConnection(connectionstring);

//OleDbCommand command = command = new OleDbCommand("select Scripcode,shortname,fullname from [" + sheetname + "]", ad);

ad.Open();

DataTable dt = ad.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

 

sheetname = dt.Rows[0]["TABLE_NAME"].ToString();

DataSet ds = new DataSet();

OleDbCommand command = new OleDbCommand("select * from [" + sheetname + "]", ad);

string q = "select * from [" + sheetname + "]";

OleDbDataAdapter oda = new OleDbDataAdapter(q, ad);

oda.Fill(ds);

 

foreach (DataRow row in ds.Tables[0].Rows)

{

string scrid = row[0].ToString();

string connect = "Data Source=ILDOT222\\SQLEXPRESS;Initial Catalog=grid;Integrated Security=True;MultipleActiveResultSets=True;";

SqlConnection cn = new SqlConnection(connect);

cn.Open();

string query = "select * from radexcel where scripcode='" + scrid + "'";

SqlDataAdapter da = new SqlDataAdapter(query, cn);

DataSet dst = new DataSet();

da.Fill(dst);

if (dst.Tables[0].Rows.Count > 0)

{

}

else

{

string sqlquerry = "insert into excel1 values ('" + row[0].ToString() + "','" + row[1].ToString() + "','" + row[2].ToString() + "')";

SqlDataAdapter adpt = new SqlDataAdapter(sqlquerry, cn);

DataSet dtset = new DataSet();

adpt.Fill(dtset);

Label1.Text = "succesfull";

}

 

}

}

}


 


 here is the .aspx code

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<telerik:RadScriptManager ID="RadScriptManager1" runat="server">

</telerik:RadScriptManager>

<telerik:RadScriptBlock runat="server">

<script type="text/javascript">

var $ = $telerik.$;

var uploadsInProgress = 0;

 

function onFileSelected(sender, args) {

if (!uploadsInProgress)

$("#Upload").attr("disabled", "disabled");

uploadsInProgress++;

}

function onFileUploaded(sender, args) {

decrementUploadsInProgress();

}

function onUploadFailed(sender, args) {

decrementUploadsInProgress();

}

function decrementUploadsInProgress() {

uploadsInProgress--;

if (!uploadsInProgress)

$("#Upload").removeAttr("disabled");

}

 

 

 

 

</script>

</telerik:RadScriptBlock>

<div>

<telerik:RadAsyncUpload ID="RadAsyncUpload1" runat="server" OnClientFileUploadFailed="onUploadFailed"

OnClientFileSelected="onFileSelected" OnClientFileUploaded="onFileUploaded" ReadOnlyFileInputs="true">

</telerik:RadAsyncUpload>

<asp:Label ID="Label1" runat="server" ></asp:Label>

<br />

<br />

<br />

<br />

<br />

<asp:Button ID="Upload" Text="UPLOAD" runat="server" onclick="Upload_Click" />

</div>

</form>

</body>

</html>




  Please paste ur code  here its urgent.......I dont have access to all the sites

  
Jitendra Faye replied to Vidyasagar Patil on 05-May-11 08:50 AM

Follow this sample code-

UploadedFile file = radAsyncUpload.UploadedFiles[0];
 byte[] fileData = new byte[file.InputStream.Length];
 file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);
 cmd.Parameters.Add("@Data", SqlDbType.Image);
 cmd.Parameters["@Data"].Value = fileData;


for more detail follow this link-
http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandradasyncupload/defaultcs.aspx?product=upload
Ravi S replied to Vidyasagar Patil on 05-May-11 08:51 AM
HI

try this example

The below is the code where i will read it as bytes and display the image.

protected void AsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
    {

      checkThum.Width = Unit.Pixel(97);
      checkThum.Height = Unit.Pixel(60);
      if (e.File.FileName.Length <= 150)
      {
        byte[] imageData = new byte[e.File.ContentLength];

        using (Stream stream = e.File.InputStream)
        {
          stream.Read(imageData, 0, (int)e.File.InputStream.Length);
        }

        checkThum.Visible = true;
        checkThum.DataValue = imageData;

      }
      else
      {
        checkThum.Visible = false;

      }

    }





The below is the button click event which is hidden when i choose a file from a Radupload this button1_click will be fired.

  protected void Button1_Click(object sender, EventArgs e)
    {
      if (RadUpload1.UploadedFiles.Count > 0)
      {
        if (AsyncUpload1.UploadedFiles.Count > 0)
        {
          AsyncUpload1.TargetFolder = System.Configuration.ConfigurationSettings.AppSettings["NetworkSmallImageUrl"];
          UploadedFile ufImage = AsyncUpload1.UploadedFiles[AsyncUpload1.UploadedFiles.Count - 1];

          string imgFileNameMaster = DateTime.Now.TimeOfDay.Ticks.ToString() + ufImage.FileName;
          string strImgPathMaster = System.Configuration.ConfigurationSettings.AppSettings["NetworkSmallImageUrl"] + imgFileNameMaster;
          string FolderPathMaster = Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["NetworkSmallImageUrl"]) + imgFileNameMaster;
          new PictureFunctions().IsResizeRadUploadImageWithWhiteBackroundFilled(ufImage, FolderPathMaster, 80, 56);

          ViewState["LogoPath"] = strImgPathMaster;

        }
}
}

hope it helps you...

Vidyasagar Patil replied to Ravi S on 10-May-11 01:01 AM

  Hi Sam

    I am still not able to upload a file in the database............... I have used the code given by you but i am getting an error in the Inputstream line.  The Error is
  Could not find file 'D:\vidyasagar\trialfolder\WebApplication2\WebApplication2 \App_Data\RadUploadTemp\2clhl2nf.xny'.

    here is my code 

  

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using Telerik.Web.UI;

using System.IO;

using System.Diagnostics;

using System.Text;

using System.Web.Configuration;

namespace WebApplication2

{

public partial class radasyncupload1 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

private List<Telerik.Web.UI.UploadedFileInfo> uploadedFiles = new List<Telerik.Web.UI.UploadedFileInfo>();

public List<Telerik.Web.UI.UploadedFileInfo> UploadedFiles

{

get { return uploadedFiles; }

set { uploadedFiles = value; }

}

protected void Button1_Click(object sender, EventArgs e)

{

if (RadAsyncUpload1.UploadedFiles.Count>0)

{

foreach (UploadedFile file in RadAsyncUpload1.UploadedFiles)

{

UploadedFileInfo uploadedFileInfo = new UploadedFileInfo(file);

UploadedFiles.Add(uploadedFileInfo);

Guid id = Guid.NewGuid();

string mimetype = "";

string filepath = file.FileName;

string strFileName = Server.MapPath(@"~\uploads\" + filepath);

string c = Path.GetFileName(strFileName);

string extension = Path.GetExtension(strFileName).ToLower();

int filesize = file.ContentLength;

SqlConnection connect = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);

string con = ConfigurationManager.AppSettings["files"].ToString();

string[] abc = con.Split(',');

for (int i = 0; i < abc.Length; i++)

{

string s = abc[i];

if (extension == s)

{

string query = "insert into fileupload1 ([Filebinary],[mimetype],[uniqueid],[Filenames],[Filesize]) values(@filebinary,@mimetype,@unique,@filenames,@filesize)";

SqlCommand mycommand = new SqlCommand(query, connect);

if (i == 0)

{

mycommand.Parameters.AddWithValue("@mimetype", mimetype).Value = "application/msword";

}

//else if(s == ".txt")

else if (i == 1)

{

mycommand.Parameters.AddWithValue("@mimetype", mimetype).Value = "application/txt";

}

mycommand.Parameters.AddWithValue("@unique", id);

mycommand.Parameters.AddWithValue("@filenames", c);

mycommand.Parameters.AddWithValue("@filesize", filesize);

 

byte[] imagebytes = new byte[file.InputStream.Length];

file.InputStream.Read(imagebytes, 0, imagebytes.Length);

 

mycommand.Parameters.AddWithValue("@filebinary", imagebytes);

connect.Open();

mycommand.ExecuteNonQuery();

connect.Close();

Label1.Text = "Your File Uploaded Sucessfully";

break;

}

else

{

Label1.Text = "Select a proper file";

}

}

}

}

else

{

Label1.Text = "Select a File";

}


}

protected void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)

{

const string relativePath = "~/uploads/";

var filename = e.File.FileName;

//var parentID = Convert.ToInt32(GridView1.SelectedValue);

var filesize = Convert.ToInt32(e.File.ContentLength);

var physicalSavePath = MapPath(relativePath) + filename;

 

//Save physical file on disk

e.File.SaveAs(physicalSavePath, true);

byte[] imageData = new byte[e.File.ContentLength];

 

using (var stream = e.File.InputStream)

{

stream.Read(imageData, 0, (int)e.File.InputStream.Length);

// var length = stream.Length;

}

}


}

}




please  paste your code here and letme know what i am doing wrong.

 Thanks in advance