Upload Download Files using Web Service in ASP.Net

Last Reply on Jul 14, 2014 06:48 PM By Mudassar

Posted on Jul 14, 2014 06:47 PM

hi
My web service Return Files bytes Correctly .
service Code is as Follows...

 

[WebMethod()]
public byte[] Download_Files_From_Database1(string File_ID)
{
try
{ 
byte[] buffer = null;
using (SqlConnection con = new SqlConnection("ConnString"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ID,File_Name,File_Extension,File_Content_types,File_Size,File_Uploaded_Date,File_Data from dbo.File_Information (nolock) where Id=@Id";
cmd.Parameters.AddWithValue("@id", File_ID);
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
buffer = new byte[Convert.ToInt32(dr["File_Size"])];
buffer = (byte[])dr["File_Data"];
}
}
}
return buffer;
}
catch (Exception ex)
{
throw ex;
}
}

and Client Side Code is

protected void lnkDownload1_Click(object sender, EventArgs e)
{
Stream download = null;
try
{
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
int fileid = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Values["ID"].ToString());
string File_Name = GridView1.DataKeys[gvrow.RowIndex].Values["File_Name"].ToString();
string File_Content_types = GridView1.DataKeys[gvrow.RowIndex].Values["File_Content_types"].ToString();
string Ext = GridView1.DataKeys[gvrow.RowIndex].Values["File_Extension"].ToString();

//// Url Working Perfect
string url = "http://localhost:13817/Web_Service_File_Download_Service_Side_Example2/WebService.asmx/Download_Files_From_Database1?File_ID=" + fileid;

HttpWebRequest Request_From_Client = WebRequest.Create(url) as HttpWebRequest;
Request_From_Client.Method = "GET";
HttpWebResponse response_From_Server = Request_From_Client.GetResponse() as HttpWebResponse;
Stream stream = response_From_Server.GetResponseStream();

Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + File_Name);

const int bufferLength = 10000;
byte[] buffer = new Byte[bufferLength];
int length = 0;

download = stream;
do
{
if (Response.IsClientConnected)
{
length = download.Read(buffer, 0, bufferLength);
Response.OutputStream.Write(buffer, 0, length);
buffer = new Byte[bufferLength];
}
else
{
length = -1;
}
}
while (length > 0);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write("Error : " + ex.Message);
}
finally
{
if (download != null)
download.Close();
}
}

can any body help me.
when i hit url it gives required Output.
but not using in above code

Posted on Jul 14, 2014 06:48 PM

First of all you must paste code properly using Add Code button provided so that anyone can read it.

You may try

http://www.techrepublic.com/article/create-a-simple-file-transfer-web-service-with-net/

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html