insert Image in database - asp.net

I am new to asp.net and databases! I am trying to save image into database from the file upload control. i have tried it but it isn't working that is upon clicking the submit button, the data does not get added into the database neither showing any error! this is the code which I have tried
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile && Page.IsValid) //fileUpload and submit
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".jpg")
{
Labelupload.Text = "Only Files with .jpg extension are allowed";
Labelupload.ForeColor = System.Drawing.Color.Red;
}
else
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + FileUpload1.FileName));
Labelupload.Text = "File Uploaded";
Labelupload.ForeColor = System.Drawing.Color.DeepSkyBlue;
LabelSubmit.Text = "Submitted Succesfully";
LabelSubmit.ForeColor = System.Drawing.Color.DeepSkyBlue;
}
}
else
{
Labelupload.Text = "Please select a file";
Labelupload.ForeColor = System.Drawing.Color.Red;
LabelSubmit.Text = "Failed to Submit";
LabelSubmit.ForeColor = System.Drawing.Color.Red;
}
// insert into database
Work obj = new Work();
/* Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);*/
obj.listItem_1 = DropDownList1.SelectedValue;
obj.listItem_2 = DropDownList2.SelectedValue;
obj.Description = TextBoxdescription.Text;
obj.Date = TextBoxdate.Text;
//obj.UploadedImage = bytes;
int k = obj.insertmethod();
TextBoxdescription.Text = "";
}
Here is the Work class that contains the insertmethod() logic:
public class Work
{
Clssqlconnection obj = new Clssqlconnection();
public string listItem_1 { get; set; }
public string listItem_2 { get; set; }
public string Description { get; set; }
public string Date { get; set; }
//public Byte[] UploadedImage { get; set; }
public int insertmethod()
{
obj.str = #"insert into [assign_Work] (listItem_1, listItem_2, Description, Date, UploadedImage)" +
"values('" + listItem_1 + "','" + listItem_2 + "','" + Description + "','" + Date + "','" + UploadedImage + "')";
return obj.ExecuteNonQuery();
}
}

The image needs to go into the database via a parameter. You cannot have it in a raw SQL statement. Try this:
public int insertmethod()
{
obj.str = #"insert into [assign_Work] (listItem_1, listItem_2, Description, Date, UploadedImage)" +
"values('" + listItem_1 + "','" + listItem_2 + "','" + Description + "','" + Date + "', ?)";
obj.Parameters.AddWithValue("File", UploadedImage);
return obj.ExecuteNonQuery();
}
Also, btw, you might want to consider using parameters for all of these values to avoid injection attacks. For instance, what if your Description field had an apostrophe in it?

Related

Add Multiple Images as Inline Attachment in Email Message Body

I am trying to add multiple png images as inline attachments to email body. My email body only has the last image. Looks like the memorysteam was overwritten new one. I tried to use AlternateView as this post suggested How to attach multi images in email body in windows application?. But it does not show any image. How to add multiple images attachments? Thanks.
struct Webpage
{
public string Id { get; set; }
public Byte[] Img { get; set; }
public string SiteName { get; set; }
public DateTime CollectTime { get; set; }
}
//
static void SendMultileImgsWEmail(List<Webpage> msg)
{
MailMessage mailMessage = new MailMessage();
SmtpClient client = new SmtpClient(mailserver);
mailMessage.IsBodyHtml = true;
mailMessage.From = new MailAddress(From);
mailMessage.To.Add(new MailAddress(To));
mailMessage.Subject = "xxx";
foreach (Webpage item in msg)
{
byte[] image = item.Img;
Attachment att = new Attachment(new MemoryStream(item.Img), item.SiteName);
att.ContentDisposition.Inline = true;
att.ContentId = item.Id;
att.ContentType.MediaType = "image/png";
mailMessage.Body += "Website Name: " + item.SiteName + Environment.NewLine + Environment.NewLine;
mailMessage.Body += "Screenshot Time: " + item.CollectTime + Environment.NewLine + Environment.NewLine;
mailMessage.Body = String.Format( #"<img src=""cid:{0}"" />", att.ContentId);
mailMessage.Attachments.Add(att);
}
//send message
try
{
client.Send(mailMessage);
}
catch (Exception ex)
{
throw;
}
}

MVC UPLOAD IMAGE SAVE IN SQL using ado.net with update (i edit any text box . the image disappear)

[HttpPost]
public ActionResult Create(Showroom showroom)
{
objShowroom.InsertShowroomDetails(showroom);
return RedirectToAction("Index");
}
I had separate data access layer
how to update the upload image in database
insert query no problem with that
if I edit any textbox image will disappear in postback or roundtrip
5. I will use not entity framework so I want to connect with model using ado.net
model folder:
public int UpdateShowroomDetails(Showroom objShowroom)
{
sqlCommandText = "Update Showroom Set CARIMAGE='" + objShowroom.CARIMAGE + "', CARNAME='" + objShowroom.CARNAME + "', CARBRAND='" + objShowroom.CARBRAND + "', PRICE=" + objShowroom.PRICE + " Where ID="+objShowroom.ID ;
return objDAL.ExecuteNonQuery(sqlCommandText);
}
Here is how i save d my image to db using ado.net . Hope this will help you
string fileName = string.Empty;
string servr_path = string.Empty;
string serviceId = string.Empty;
string planId = string.Empty;
if (IdProofFile.HasFile && IdProofFile.PostedFile.FileName != "")
{
string fileType = IdProofFile.PostedFile.ContentType;
if (fileType == "image/jpg" || fileType == "image/jpeg" || fileType == "image/png" || fileType == "image/gif")
{
int fileSize = IdProofFile.PostedFile.ContentLength;
if (fileSize <= 2097152)
{
//fileName = System.IO.Path.GetFileName(IdProofFile.PostedFile.FileName);
fileName = "ID-" + txt_FirstName.Text + "_" + txt_LstName.Text + DateTime.Now.ToString("ddmmyy_hhMMss") + Path.GetExtension(IdProofFile.PostedFile.FileName);
string serverFolder = Server.MapPath("idProof//");
if (!System.IO.Directory.Exists(serverFolder))
{
System.IO.Directory.CreateDirectory(serverFolder);
}
servr_path = serverFolder + fileName;
foreach (int i in ddlservices.GetSelectedIndices())
{
serviceId += "," + ddlservices.Items[i].Value;
}
IdProofFile.SaveAs(servr_path);
}
}
else
{
}
}
else
{
}
}
else
{
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "mask();", true);
mpepopup.Show();
lblMsg.Text = "Min File Size Must Be Greater Than 5 KB and Less Than 2 MB";
}
}
else
{
mpepopup.Show();
// ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "mask();", true);
lblMsg.Visible = true;
lblMsg.Text = "Please upload an image of *.jpg/*.jpeg/*.png/*.gif/*.bmp file type only!!!";
}
}
else
{
mpepopup.Show();
lblMsg.Text = "ID Proof File Not Selected.";
}

MVC Action not returning csv file. ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION

I want to get data from database and show it in CSV file. Following is my code for getting data from db.
public ActionResult GetTNStateUnemploymentReport(int quarter, int year, int payrollState, long? fromClientId, long? toClientId, string fromClient, string toClient)
{
//if (fromClient == "" && toClient == "")
//{
// fromClientId = 0;
// toClientId = 0;
//}
string quarterMonths = "";
if (quarter == 1)
quarterMonths = "Jan, Feb, Mar";
else if (quarter == 2)
quarterMonths = "Apr, May, Jun";
else if (quarter == 3)
quarterMonths = "Jul, Aug, Sep";
else if (quarter == 4)
quarterMonths = "Oct, Nov, Dec";
var modelList = new PayrollHelper().GetTNStateUnemploymentReport(quarter, year, fromClientId ?? 0, toClientId ?? 0);
var csv = new System.Text.StringBuilder();
foreach (var model in modelList)
{
csv.Append(string.Format("{0}{1}", model.StringData, Environment.NewLine));
}
return new CSVResult
{
FileName = "TN_" + quarterMonths + "_" + year.ToString() + ".csv",
Content = csv.ToString()
};
Following is my CSVResult class which I am using to create the CSV File.
public class CSVResult: ActionResult
{
public string FileName { get; set; }
public string Content { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Buffer = true;
context.HttpContext.Response.Clear();
context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
context.HttpContext.Response.ContentType = "application/csv;charset=utf-8";
context.HttpContext.Response.Write(Content);
context.HttpContext.Response.End();
}
}
I am getting the following error:
LOCAL HOST SENT INVALID RESPONSE
ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION.
I have another report which creates CSV file using above mentioned ExecuteResult method and is working fine, but the current one is not.
Based on your code "TN_" + quarterMonths + "_" + year.ToString() + ".csv" a file name would look like this
"TN_Jul, Aug, Sep_2016.csv"
which, based on .AddHeader("content-disposition", "attachment; filename=" + FileName) would result in a content disposition that looks like this
"Content-Disposition: attachment; filename=TN_Jul, Aug, Sep_2016.csv"
The commas and spaces in the filename when generating the content disposition will cause issues with some browsers.
Now there are a few ways to fix this.
1) You could change the way you generate the filename to replace spaces and commas (,) with underscores (_)
for example instead of
quarterMonths = "Jan, Feb, Mar";
change them to
quarterMonths = "Jan_Feb_Mar";
resulting in a filename that looks like
"TN_Jul_Aug_Sep_2016.csv"
2) You could also make sure to enclose the filename in "" (double quotes)
So instead of
.AddHeader("content-disposition", "attachment; filename=" + FileName)
change it to
.AddHeader("content-disposition", "attachment; filename=\"" + FileName + "\"");
or
.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", FileName));
UPDATE:
Using ideas from the source code for System.Web.Mvc.FileResult You could rewrite your CsvResult to allow for the suggested changes I mentioned above.
public class CsvResult : ActionResult {
private const string CONTENT_TYPE = "application/csv;charset=utf-8";
private string filename;
public CsvResult() {
System.Net.Http.Headers.MediaTypeHeaderValue headerValue = null;
if (System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(CONTENT_TYPE, out headerValue)) {
ContentType = headerValue.ToString();
}
}
public string ContentType { get; private set; }
public string FileName {
get { return filename ?? String.Empty; }
set { filename = value; }
}
public string Content { get; set; }
public override void ExecuteResult(ControllerContext context) {
HttpResponseBase response = null;
if (context != null
&& context.HttpContext != null
&& ((response = context.HttpContext.Response) != null)) {
response.Buffer = true;
response.Clear();
response.ContentType = ContentType;
if (!String.IsNullOrWhiteSpace(FileName)) {
string headerValue = ContentDispositionUtil.GetHeaderValue(FileName);
response.AppendHeader("Content-Disposition", headerValue);
}
response.Write(Content);
response.End();
}
}
internal static class ContentDispositionUtil {
public static string GetHeaderValue(string filename) {
System.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition = null;
string headerValue = String.Format("attachment; filename=\"{0}\"", filename);
if (System.Net.Http.Headers.ContentDispositionHeaderValue.TryParse(headerValue, out contentDisposition)) {
var result = contentDisposition.ToString();
return result;
} else {
throw new ArgumentException("Content Disposition Header Value not well formatted - " + headerValue, "FileName");
}
}
}
}
Why not use standard result deriving from FileResult instead?
FileResult Class
One of the 3 concrete classes should do what you want. If you write your own ActionResult then it is up to you to write correct code.

asp.net upload control is not working in ipad

The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?

Asp.net Session Url Asp.net Page.IsPostBack getuserinfo error

Okay,The Other errors are fixed now im at this point where my other pages need their code to be updated:
Error : Object reference not set to an instance of an object.
public partial class Controls_GetUserScraps : System.Web.UI.UserControl
{
DataBaseClass dbClass = new DataBaseClass();
public DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetUserScraps(int.Parse(Session["UserId"].ToString()));
}
}
public void GetUserScraps(int Id)
{
string getUserScraps = "SELECT u.Id as UserId,u.FirstName,,u.LastName,u.ImageName,s.FromId,s.ToId,s.Message,s.SendDate,s.ID as ScrapId FROM [User] as u, Scrap as s WHERE u.Id=s.FromId AND s.ToId='" + Request.QueryString["Id"].ToString() + "'";
dt = dbClass.ConnectDataBaseReturnDT(getUserScraps);
if (dt.Rows.Count > 0)
{
GridViewUserScraps.DataSource = dt;
GridViewUserScraps.DataBind();
}
}
I replaced Session ID to UserId and it removed the error now it has displayed another error under.
Error : Object reference not set to an instance of an object.
string getUserScraps = "SELECT u.Id as UserId,u.FirstName,,u.LastName,u.ImageName,s.FromId,s.ToId,s.Message,s.SendDate,s.ID as ScrapId FROM [User] as u, Scrap as s WHERE u.Id=s.FromId AND s.ToId='" + Request.QueryString["Id"].ToString() + "'";
Adding your fix created this new error:
I think the easiest way to do this would be to have the private bool UserAuthenticate method take an out parameter which you can use to return the actual user name from the database.
private bool UserAuthenticate(string UserName, string Password, out string actualUserName)
{
actualUserName = string.Empty;
bool boolReturnValue = false;
//--------------------------------
//Check UserID From Config File
if (UserName == "User" && Password == "Pass")
{
boolReturnValue = true;
return boolReturnValue;
}
else
{
//--------------------------------
dt = new DataTable();
string chkUser = "Select * FROM [User] where Email='" + UserName + "' AND Password='" + Password + "'";
dt = dbClass.ConnectDataBaseReturnDT(chkUser);
if (dt.Rows.Count > 0)
{
//TODO: grab the actual user name from the row and assign it to actualUserName. For example:
actualUserName = dt.Rows[0]["FullName"];
boolReturnValue = true;
Session["UserId"] = dt.Rows[0]["Id"].ToString();
string updateLastLogin = "Update [User] SET LastLogin='" + System.DateTime.Now.ToString() + "' where Id='" + Session["UserId"].ToString() + "'";
dbClass.ConnectDataBaseToInsert(updateLastLogin);
}
return boolReturnValue;
}
}
After that you would then need to do something like this in the OnAuthenticate method:
string actualUserName;
Authenticated = UserAuthenticate(ctlLogin.UserName, ctlLogin.Password, out actualUserName);
And the redirect would now be:
Response.Redirect("Home.aspx/" + actualUserName);

Resources