Why I am getting one more character? - c#

Hello Im using this C# code for images upload.
protected void UploadFile(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO foto(FileName, ContentType, Content) VALUES (#FileName, #ContentType, #Content)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#FileName", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Content", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
I upload the image in a longblob field, then to show the image I am using C# WebService, AJAX, JavaScript, converting the image to Base64String but image is displayed like if do not exist.
Here is my Base64String:
Base64String
As you can see the problem is with this extra characters:
AAEAAAD/////AQAAAAAAAAAPAQAAAHgBAAAC
Why this happen? And how can I solve it?

can you replace the bellowed lines with your above code
protected void UploadFile(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
System.Drawing.Image imagetuUpload = System.Drawing.Image.FromStream(fs);
Bitmap bitmap = new Bitmap(imagetuUpload);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] upproimag = new byte[stream.Length + 1];
stream.Read(upproimag, 0, upproimag.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO foto(FileName, ContentType, Content) VALUES (#FileName, #ContentType, #Content)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#FileName", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Content", upproimag);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
i hop it may help you :)

long time back i was in same issue i do not remember other than doing this at that time:
I check if I am wrong or not going here:
http://jsfiddle.net/hpP45/
I try to decode first(google bse64 decoder )
https://www.base64decode.org/
and save decoded binary data as an jpeg file and open it.
if it does not open then i guess,there might be issue on your base64 encoding

Related

Opening the varbinary column in a popup window using contenttype

I am making a file uploader using html tags. I have id, Name and Data in my table. Data is storing the contents of the file in binary format in a column of datatype varbinary(max). I am able to successfully upload the file and I am also able to read the byte array back.
Code for upload at code behind:
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into FileUploader2 values (#Name, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Context.Response.Write("Uploaded Successfully!");
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
I am also creating a grid which shows me list of files along with an icon which when clicked will view me the file after reading the byte array. I have a JS function on that onclick which I am accessing through WebMethod at code-behind. Following is my code when user clicks on view icon:
[System.Web.Services.WebMethod]
public static void ShowDocument()
{
string filename = string.Empty;
string contentType = string.Empty;
byte[] bytes = null;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
using (SqlCommand com = new SqlCommand("SELECT * FROM FileUploader2", con))
{
using (SqlDataReader reader = com.ExecuteReader())
{
if (reader.Read())
{
filename = (string)reader["Name"];
contentType = (string)reader["ContentType"];
bytes = (byte[])reader["Data"];
}
}
}
}
System.Web.HttpContext.Current.Response.ContentType = contentType;
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;
filename=" + filename);
System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
System.Web.HttpContext.Current.Response.Flush();
}
This code is working fine as well and correctly reads all the columns. Now after reading, I want to view the file as well in a pop window. How can I do so? I think I have to take contenttype to let it know what type of file I want to open and then use the bytes to do so. But I have no idea how to achieve that.

Store a File Size in a database table using file upload controle

I need to save a file size in database table while uploading a file in using upload control.
i am simple pitching my upload control code here.
Please take a look.
protected void UploadFileControl(object sender, EventArgs e)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
using (SqlConnection con = new SqlConnection(con))
{
string str = "INSERT INTO XYZ VALUES (#FileName, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(str))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#FileName", fileName);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
This is simple upload control code.

lable don't show the message

i have problem with the lable when i upload file into database it not show any message
c#
protected void btnUpload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["homeworkConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles (FileName,ContentType,Number,Date,Data) values (#Name, #ContentType,#number,getDate(), #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#number", Session["id"].ToString());
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
fname.Visible = true;
fname.Text = "file Has been uploaded";
}
}
}
asp.net code
<asp:Label ID="fname" runat="server" Text="Label" Visible="False"></asp:Label>
the lable work with insert value but not work with the uploading file
protected void btnUpload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["homeworkConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles (FileName,ContentType,Number,Date,Data) values (#Name, #ContentType,#number,getDate(), #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#number", Session["id"].ToString());
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
fname.Visible = true;
fname.Text = "file Has been uploaded";
}
Try Like this...

How to display Image using repeater

I have a page to upload a photo into my database. Then when I click upload, the photo has been saved as binary format in database:
protected void Button1_Click(object sender, EventArgs e)
{
Byte[] bytes = null;
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filePath = Path.GetFileName(filename);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "','" + bytes + "')", con);
con.Open();
cmd.ExecuteNonQuery();
When I am trying to retrieve image then it is not displayed, how to display image using repeater?
Database: menu image
<asp:Image ID="ViewPhotoImage" runat="server" ImageUrl='<%# GetImage(Eval("menu")) %>' Height="190px" Width="180px"/>
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[]) img);
}
I think your problem may be in how you are putting the data into the database. You may not have valid image data in the database at all. Does that code run for you when you upload an image? When I run it it errors out on the sql command because when you implicitly convert a byte[] into a string in c# you get "System.Byte[]" instead of the string representation of the data. You need to convert that byte[] into a binary string. That link has a bunch of ways to do it, and here's your upload code with one of those ways (Not Recommended, see below):
(Edited, see comment below)
Byte[] bytes = null;
string hex = "0";
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filePath = Path.GetFileName(filename);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
hex = "0x" + BitConverter.ToString(bytes).Replace("-", "");
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "'," + hex + ")", con);
con.Open();
cmd.ExecuteNonQuery();
You also might want to move that sql code into the if block, but maybe that's what you want, just thought i'd mention it in case.
HOWEVER...
I would be remiss if I did not strongly suggest that you parameterize your sql statement to avoid injection attacks. But not only is it better for security, it makes working with the binary data much easier as there is no need to string convert. Here's the relevant code with parameters:
Byte[] bytes = null;
if (FileUpload1.HasFile)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES(#disc, #menu)", con);
cmd.Parameters.AddWithValue("#disc", TextBox.Text);
cmd.Parameters.AddWithValue("#menu", bytes);
con.Open();
cmd.ExecuteNonQuery();
Once I did that, your other code worked fine and I was able to see my test images in the repeater. I hope that helps!

Upload data on a button click event

I am new to programming. I want to be able to upload files on a website that save into my database when I upload the file and the send an email of the files that I uploaded to two other parties
how can I achieve this goal?
This is the code that I currently have but I get errors of file name does not exist in current context?
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles values (#Name, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#File Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
protected void Upload_Bt1_Click(object sender, EventArgs e)
{
MailMessage mailObj = new MailMessage(
txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
SmtpClient SMTPServer = new SmtpClient("127.0.0.1");
try
{
SMTPServer.Send(mailObj);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}

Categories