Wednesday, February 18, 2015

save image in to data base and get image from database using jquery

Posted by Gnani Palepu  |  No comments


     save image in to data base and get image from database using jquery  
 -----------------------------------------------------------------     ----  
 here two thing   
 1). converting the image to binary and save into the databse  
 2). converting the binary data to the image for dispaly.  
 Step 1:  
 ---------  
 * i am writing the code for upload button in html  
 * give proper id and all.  
 Html:  
 ======  
 <div class="col-md-5 col-sm-5">  
                          <div class="form-group">  
                               <div class="upload-photo"><center>  
                                    <img src="../../Designing/images/defaultuserpic.png" class="img-responsive user uploadimageclass" />  
                                    </center><div class="uploda-text">  
                                         Home Image – Upload  
                                         <div class="_3jk">  
                 <input type="file" name="filUpload" class="_n _5f0v" id="HomeimagefilUpload" title="Choose a photo to upload" accept="image/*"  
                       tabindex="8" onchange="showimagepreview(this)" />  
                              <input style="color: Black" type="hidden" id="Homeimagefilenames" />  
                                         </div>  
                                    </div>  
                               </div>  
                          </div>  
                </div>  
 step 2:  
 ------  
 put in page load, if you want declare some sessions orther wise write normally.  
 if (Request.Files.Count > 0)  
       {  
         Session[CommonConstants.FILE] = Request.Files[0];  
         Response.Cookies["File"].Value = Request.Files[0].ToString();  
       }  
 step 3):  
 here i am writing the code. after uploading for preview.  
 //showimagepreview function starts here  
 function showimagepreview(sender) {  
   var validExts = new Array('.jpeg', '.jpg', '.gif', '.png');  
   var fileExt = sender.value;  
   fileExt = fileExt.substring(fileExt.lastIndexOf('.'));  
   if (validExts.indexOf(fileExt) < 0) {  
     alert("Invalid file selected, valid files are of " +  
             validExts.toString() + " types.");  
     $("#HomeimagefilUpload").val('');  
     $('.uploadimageclass').attr('src', '../../Designing/images/defaultuserpic.png');  
   } else {  
     callingpreviewimage(sender);  
     SaveImages();  
     $('#Homeimagefilenames').val(sender.value);  
   }  
 } // showimagepreview function end here  
 //callingpreviewimage function starts here  
 function callingpreviewimage(input) {  
   if (input.files && input.files[0]) {  
     var filerdr = new FileReader();  
     filerdr.onload = function (e) {  
       $('.uploadimageclass').attr('src', e.target.result)  
     }  
     filerdr.readAsDataURL(input.files[0]);  
   }  
 } // callingpreviewimage function ends here  
 //saveimages function starts here  
 function SaveImages() {  
   var formData = new FormData();  
   var file = document.getElementById("HomeimagefilUpload").files[0];  
   $('#Homeimagefilenames').val(file.name);  
   formData.append("file", file);  
   formData.append("filename", file.name);  
   formData.append("filesize", file.size);  
   formData.append("fiketype", file.type);  
   var uploadServerSideScriptPath = "UserMaster.aspx";  
   var xhr = new XMLHttpRequest();  
   xhr.open("POST", uploadServerSideScriptPath);  
   xhr.send(formData);  
 }  
 step 4:  
 ===========  
 in request   
       public Byte[] UserImg { get; set; }  
      public Int32 ImgType { get; set; }  
 step 5):  
 ==========  
 in aspx.cs  
 #region SaveGlobalSettings  
     /// <summary>  
     /// Save User Master  
     /// </summary>  
     /// <param name="request"></param>  
     /// <returns></returns>  
     ///   
     [System.Web.Script.Services.ScriptMethod, System.Web.Services.WebMethod]  
     public static GlobalSettingsResponse SaveGlobalSettingsValues(GlobalSettingsRequest request)  
     {  
       var response = new GlobalSettingsResponse();  
       try  
       {  
         if (request.ImgType == 1)  
         {  
           HttpPostedFile file = (HttpPostedFile)HttpContext.Current.Session[CommonConstants.HOMEIMAGEFILE];  
           int filelenght = file.ContentLength;  
           Byte[] imagebytes = new Byte[filelenght];  
           file.InputStream.Read(imagebytes, 0, filelenght);  
           request.Homeimage = imagebytes;  
         }  
         response = BusinessFactory<UtilitiesBO>.Instance.SaveGlobalSettings(request);  
       }  
       catch (Exception ex)  
       {  
         ExceptionManager.HandleException(ex, request);  
         throw;  
       }  
       return response;  
     }  
     #endregion SaveGlobalSettings  
 Bo  
 =============:  
     #region Save Global Settings  
     public GlobalSettingsResponse SaveGlobalSettings(GlobalSettingsRequest request)  
     {  
       var response = new GlobalSettingsResponse();  
       response = DataAccessFactory<UtilitiesDAO>.Instance.SaveGlobalSettings(request);  
       if (response.ResponseCode == 1)  
       {  
         response.IsValid = true;  
         response.ResponseMessage = Utilities.GetMessage("A02");  
       }  
       else  
       {  
         response.IsValid = false;  
         response.ResponseMessage = Utilities.GetMessage("A04");  
       }  
       return response;  
     }  
     #endregion Save Global Settings  
 DAO  
 ------  
     #region Save Global Settings  
     public GlobalSettingsResponse SaveGlobalSettings(GlobalSettingsRequest request)  
     {  
       var response = new GlobalSettingsResponse();  
       Database db = DatabaseFactory.CreateDatabase(CommonConstants.CONNECTIONNAME);  
       using (DbCommand dbCommand = db.GetStoredProcCommand(StoredProcedures.spsaveGlobalSettings))  
       {  
         //db.AddInParameter(dbCommand, DBParameter.DocDesignerAppPath, DbType.String, request.DocDesignerAppPath);  
         //db.AddInParameter(dbCommand, DBParameter.Formatoutput, DbType.String, request.Formatoutput);  
         //db.AddInParameter(dbCommand, DBParameter.WhenFrmOpensNewBtn, DbType.String, request.WhenFrmOpensNewBtn);  
         //db.AddInParameter(dbCommand, DBParameter.DefaultNewMode, DbType.String, request.DefaultNewMode);  
         //db.AddInParameter(dbCommand, DBParameter.MarqueeMsg, DbType.String, request.MarqueeMsg);  
         db.AddInParameter(dbCommand, DBParameter.Homeimage, DbType.Binary, request.Homeimage);  
         db.AddInParameter(dbCommand, DBParameter.ImgType, DbType.Int32, request.ImgType);  
         db.AddOutParameter(dbCommand, DBParameter.ResponseCode, DbType.Int32, 20);  
         db.ExecuteNonQuery(dbCommand);  
         response.ResponseCode = Convert.ToInt32(db.GetParameterValue(dbCommand, DBParameter.ResponseCode));  
       }  
       return response;  
     }  
     #endregion Save Global Settings  
 sp  
 ===== change your table names and id  
 for insertion  
 USE [EFACTIC_DEV]  
 GO  
 /****** Object: StoredProcedure [dbo].[USP_ADD_USER_NEW_RIGHTS]  Script Date: 02/13/2015 14:23:37 ******/  
 SET ANSI_NULLS ON  
 GO  
 SET QUOTED_IDENTIFIER ON  
 GO  
 -- =============================================  
 -- Author:          gopal  
 -- Create date: 02/12/2014  
 -- Description:     save user rights  
 -- =============================================  
 ALTER PROCEDURE [dbo].[USP_ADD_USER_NEW_RIGHTS]  
      @UserImg          VARBINARY(MAX)          =     NULL  
      ,@ResponseCode     BIGINT                    OUTPUT  
 AS  
 BEGIN  
      BEGIN TRY  
                INSERT     INTO MstUser (UserImage)   
                               VALUES     (@UserImg)  
                SET @ResponseCode=IDENT_CURRENT('MstUser')  
      END TRY  
      BEGIN CATCH  
           SET @ResponseCode=-999  
      END CATCH            
 END  

2:21 AM Share:

0 comments:

Get updates in your email box
Complete the form below, and we'll send you the best coupons.

Deliver via FeedBurner
Proudly Powered by Blogger.
back to top