I am trying to move the saved pdf file in my database to my local drive. I cannot find a way to do it. When I click on button1 , the dialog save or open shows up. I want to save the file directly on my local drive. Any help ?
please note that reader["FileData"] contains my file.
protected void Button1_Click(object sender, EventArgs e)
{
string id = TextBox1.Text.TrimEnd();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * From FileInformation where Id=3";// +id + " ";
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Response.Clear();
//Response.Buffer = true;
Response.ContentType = reader["FileType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + reader["FileName"] + "\"");
Response.BinaryWrite((byte[])reader["FileData"]);
Response.Flush();
Response.End();
con.Close();
}
Any help on this ?
Related
protected void submit_Click(object sender, EventArgs e)
{
Label2.Text = Session["id"].ToString();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = con.CreateCommand();
con.Open();
string UpdateQuery = "Update register set name='" + name.Text + "'where email='" + Session["id"] + "'";
SqlCommand cmd3 = new SqlCommand(UpdateQuery, con);
cmd3.CommandType = CommandType.Text;
con.Close();
}
}
I want to update name record using session for user profile in asp.net.
Try like this:
using (SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
{
string strSQL = "UPDATE register set [name] = #name " +
"WHERE email = #email";
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = name.Text;
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["id"].ToString();
conn.Open();
cmd.ExecuteNonQuery();
}
}
The above will dispose/close the connection for you. And this will even close the connection if you have some error in the code.
The above also removes the messy "'" and concatenation in your code (easy to read, and maintain). And by using parameter's the code is also safe from injection.
hence:
I am using divexpress pivotgrid control.
I want to do save and restore the layout. I can do that simply by using Session.
But I don't know how to save it into my SQL Database.
This code without database
UPDATED
protected void ASPxButton1_Click(object sender, EventArgs e)
{
Session["Layout"] = ASPxPivotGrid1.SaveLayoutToString();
MemoryStream stream = new MemoryStream(byteArray);
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO [HQWebMatajer].[dbo].[ReportSave]([UserID],[ReportName],[UserFileName],[ReportData])VALUES('faisal.3012','TotalSales','faisalxxx',#ReportData)";
cmd.Parameters.AddWithValue("#ReportData", stream);
con.Open();
cmd.ExecuteNonQuery();
}
//divServer.InnerHtml = Session["Layout"].ToString();
}
protected void ASPxButton2_Click(object sender, EventArgs e)
{
string text = "";
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select reportdata from [HQWebMatajer].[dbo].[ReportSave] where UserID='faisal.3012'";
con.Open();
string xxx = cmd.ExecuteScalar().ToString();
StreamReader reader = new StreamReader(xxx);
text = reader.ReadToEnd();
}
ASPxPivotGrid1.LoadLayoutFromString(text);
}
UPDATE: Saving to database is working, but when i try to restore from database it throws the following error
System.IO.FileNotFoundException: Could not find file 'C:\Program Files (x86)\IIS Express\System.Byte[].
on this line
StreamReader reader = new StreamReader(xxx);
I don't know any idea about how to convert and where to convert. The same question asked in devexpress in this link.. They referred to this stackoverflow. But the convertion I don't understand how to make it into my scenario.
Thanks
select reportdata from [HQWebMatajer].[dbo].[ReportSave] where UserID='faisal.3012'
You check what is the output of the above line in the DB.
You may have not initialized the variable byteArray with grid data. Break code at
MemoryStream stream = new MemoryStream(byteArray);
and check what you are storing in to DB.
I have an issue with the connectionstring or something similiar I assume. since data is printed from DB but won't write to DB using the INSERT Query string.
here's the .cs code part:
protected void Page_Load(object sender, EventArgs e)
{
Load_Data();
}
protected void Load_Data()
{
DataTable dtUsers = new DataTable();
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create sql
string sql = "SELECT Username, Fullname, Email FROM Users;";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// load data to dt
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtUsers.Load(reader);
con.Close();
// print data to gridview
GridView1.DataSource = dtUsers;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create query
string sql = "INSERT INTO Users (UserName,Passowrd,Email,FullName) VALUES ('" + txtUsername.Text + "','"+ txtPwd.Text + "','"+ txtEmail.Text + "','" + txtFullName.Text + "');";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// save data to db
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
thank you!
I'm using VS2012 ASP.NET website, and I have an asp.net page where I upload files to a folder.
When I upload the files, it stores the path in SQL database tabel field like ~/Client_Info/text.docx and the file itself is saved in a folder.
Now I want to download the files I have stored by displaying it in a gridview with a download link. But after a whole day searching I cannot get a answer. Can someone help me out?
protected void lnkDownload_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender asLinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
int fileid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value.ToString());
string name, type;
using (SqlConnection con=new SqlConnection(strCon))
{
using (SqlCommand cmd=new SqlCommand())
{
cmd.CommandText = "select FileName, FileType, FileData from FileInformation where Id=#Id";
cmd.Parameters.AddWithValue("#id", fileid);
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
Response.ContentType = dr["FileType"].ToString();
Response.AddHeader("Content-Disposition",
"attachment;filename=\""
+ dr["FileName"] + "\"");
Response.BinaryWrite((byte[])dr["FileData"]);
Response.End();
}
}
}
}
In order to write a file to the Response you can use the Response.WriteFile function. It takes as a parameter the physical path of the file.
You can try the following code, assuming the file path is correct and the file exists.
Response.ContentType = dr["FileType"].ToString();
Response.AddHeader("Content-Disposition",
"attachment;filename=\""
+ dr["FileName"].ToString() + "\"");
Response.WriteFile(Server.MapPath(dr["FileName"].ToString()));
Response.End();
Friends I need your help to fix an issue.
DETAIL
I have a Registration form based on update panel (works in slides) where one slide asks the user to upload his/her photo (optional).
ISSUE
Everything works fine, fine name is saved in Database, user folder creates in server side But the file is not uploaded ... no error.
CODES
#primePhoto -- FileUpload1
protected void RegisterClick6(object sender, EventArgs e)
{
string pathToCreate = "img/users/" + userName.Text;
if (Directory.Exists(Server.MapPath(pathToCreate)))
{
}
else
{
Directory.CreateDirectory(Server.MapPath(pathToCreate));
}
String imageFolder = pathToCreate;
String savePath;
String saveFile;
if (FileUpload1.HasFile)
{
savePath = Path.Combine(Request.PhysicalApplicationPath, imageFolder);
saveFile = Path.Combine(savePath, FileUpload1.FileName);
FileUpload1.SaveAs(saveFile);
}
SqlConnection con = new SqlConnection(str1);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "RegisterUser";
cmd.Parameters.AddWithValue("#userName", userName.Text);
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#postDate", currentDate.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
cmd.Parameters.AddWithValue("#FirstName", FirstName.Text);
cmd.Parameters.AddWithValue("#LastName", LastName.Text);
cmd.Parameters.AddWithValue("#primePhoto", FileUpload1.FileName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
multiview1.SetActiveView(view7);
}
Add trigger to update panel as like:
<Triggers>
<asp:PostBackTrigger ControlID="RegisterClick6" />
</Triggers>