Ajax to achieve a picture preview and upload and generate thumbnails of the method _ajax related

Source: Internet
Author: User
Tags httpcontext

To achieve the function, upload pictures can be previewed, because there are other text, so not only upload pictures, to achieve with other text to save, of course, upload pictures, and then the path and other text to write the database, but also to create thumbnails for the picture, is only to upload pictures Text in Ajax directly pass the parameters can be, to upload more than a picture, modify it.

Learn from the online data, wrote a bit, do not need to add a new page, only in a page on the OK.

JS Code:

Ajax saves the data and implements this method in the background method function SaveData () {filename = document.getElementById ("Idfile"). Value; Result =test_test_aspx. 
    SaveData (filename). value; if (result) {alert (Save success!)      
    "); 
  return false; 
    //Implementation Preview function DrawImage (IMGD) {var prew = 118; 
    var Preh = 118; 
    var image = new Image (); 
    IMAGE.SRC = IMGD.SRC; 
      if (image.width > 0 && image.height > 0) {flag = true; 
          if (image.width/image.height >= Prew/preh) {if (Image.width > Prew) {imgd.width = Prew; 
        Imgd.height = (Image.height * prew)/image.width; 
          else {imgd.width = Image.width; 
        Imgd.height = Image.height; 
      } Imgd.alt = Image.width + "x" + image.height; 
          else {if (Image.height > Preh) {imgd.height = Preh; 
        Imgd.width = (Image.width * preh)/image.height; 
    } else {      Imgd.width = Image.width; 
        Imgd.height = Image.height; 
      } Imgd.alt = Image.width + "x" + image.height; 
    function Filechange (Value) {flag = False when idfile content changes;    
    document.getElementById ("Showimg"). Style.display = "None"; 
    document.getElementById ("Idimg"). width = 10; 
    document.getElementById ("idimg"). Height = 10; 
    document.getElementById ("Idimg"). alt = ""; 
  document.getElementById ("idimg"). src = Value;  }

The following is the foreground code:

<div class= "CBS" > 
<div class= "L" ><label> pictures:</label></div> 
<div> 
  <input id= "Idfile" name= "pic" type= "file" runat= "server" onchange= "Filechange (this.value);"/> </div 
> 
    </div>  
    <div class= "CBS" > 
<div class= "L" ><label> preview: </label></ div> 
<div> 
  // Implementation Preview 
    // This is mainly to achieve the view to display the picture, because the above (idimg) plus runat= "Server" error, if there is a good way to message     
</div> 
</div>    

The following are Ajax methods:

[Ajax.ajaxmethod ()] public bool SaveData (string filenamepath) {string serverfilename = "";   
  String sthumbfile = ""; 
  String Ssavepath = "~/files/"; 
  int intthumbwidth = 118; 
  int intthumbheight = 118; 
  String sthumbextension = "Thumb_"; 
 try {//Get the file information to save FileInfo file = new FileInfo (Filenamepath); Get file extension string filenameext = filename. 
 
 Extension; 
   Verify valid file if (Checkfileext (Filenameext)) {//Generate random filename to be saved string filename = GetFileName () + Filenameext; 
 
   Check if the saved path has/ends if (ssavepath.endswith ("/") = = false) Ssavepath = Ssavepath + "/"; 
   Save string Datepath = DateTime.Now.ToString ("yyyymm") + "/" + DateTime.Now.ToString ("dd") + "/" By date classification; 
   if (true) {Ssavepath + = Datepath; 
   //Get the file path to save Serverfilename = Ssavepath + fileName; 
 
   Physical full path string tofilefullpath = HttpContext.Current.Server.MapPath (Ssavepath); Check to see if the path does not create an if (! Directory.Exists (Tofilefullpath)) {Directory.createdirecTory (Tofilefullpath); 
 
   ///The full filename to be saved string tofile = Tofilefullpath + filename; 
   Create WebClient instance WebClient mywebclient = new WebClient (); 
   
   Set Windows network security authentication mywebclient.credentials = CredentialCache.DefaultCredentials; 
   To upload the file FileStream fs = new FileStream (Filenamepath, FileMode.Open, FileAccess.Read); 
   FileStream fs = OpenFile (); 
   BinaryReader r = new BinaryReader (FS); 
   The UploadFile method can be used in the following format//mywebclient.uploadfile (ToFile, "put", Filenamepath); byte[] Postarray = r.readbytes (int) fs. 
   Length); 
   Stream Poststream = Mywebclient.openwrite (ToFile, "put"); 
   if (poststream.canwrite) {poststream.write (Postarray, 0, postarray.length); 
   } poststream.close (); The above is the original try {//original image loaded using (System.Drawing.Image sourceimage = System.Drawing.Image.FromFile (System.Web.Http 
   Context.Current.Server.MapPath (Serverfilename)) {//original width and height int width = sourceimage.width; int height = SourceimAge. 
   Height; 
   int smallwidth; 
 
   int smallheight; Gets the size of the first drawing, (comparing the width/thumbnail of the original image and the height/thumbnail of the original image) if (((decimal) width)/height <= ((decimal) intthumbwidth)/Intthumbhei 
  ght) {smallwidth = Intthumbwidth; 
   Smallheight = Intthumbwidth * height/width; 
  else {smallwidth = Intthumbheight * width/height; 
   Smallheight = Intthumbheight; 
   //Determine if the thumbnail exists in the current folder with the name file int file_append = 0; 
 
   Sthumbfile = sthumbextension + System.IO.Path.GetFileNameWithoutExtension (fileName) + Filenameext; while (System.IO.File.Exists (System.Web.HttpContext.Current.Server.MapPath (Ssavepath + sthumbfile))) {file_append+ 
  +; Sthumbfile = sthumbextension + System.IO.Path.GetFileNameWithoutExtension (fileName) + file_append. 
   ToString () + Filenameext; 
 
   }//Thumbnail save absolute path string smallimagepath = System.Web.HttpContext.Current.Server.MapPath (ssavepath) + sthumbfile; Creates a new storyboard with a minimum proportional compression size to draw the original using (System.Drawing.Image bitmap = new SysTem. Drawing.bitmap (Smallwidth, smallheight)) {//Draw the middle graph using (System.Drawing.Graphics g = system.drawing.graphics.f 
Romimage (bitmap)) {//HD, smooth g.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.High; 
G.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
G.clear (Color.Black);  G.drawimage (Sourceimage, New System.Drawing.Rectangle (0, 0, Smallwidth, smallheight), new System.Drawing.Rectangle (0, 
  0, width, height), System.Drawing.GraphicsUnit.Pixel); //Create a new storyboard, drawing the intermediate graph using the thumbnail size (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap (Intthumbwidth, Intthumbheigh T) {//Draw the thumbnail using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage (Bitmap1)) {//HD, smooth G.int 
  Erpolationmode = System.Drawing.Drawing2D.InterpolationMode.High; 
  G.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
  G.clear (Color.Black); 
  int lwidth = (smallwidth-intthumbwidth)/2; int bheight = (smallheight-iNtthumbheight)/2; G.drawimage (Bitmap, new Rectangle (0, 0, Intthumbwidth, intthumbheight), Lwidth, Bheight, Intthumbwidth,intthumbheight, 
  GraphicsUnit.Pixel); 
  G.dispose (); Bitmap1. 
   Save (Smallimagepath, System.Drawing.Imaging.ImageFormat.Jpeg); 
   return true; A catch {//error Deletes the System.IO.File.Delete (System.Web.HttpContext.Current.Server.MapPath (SE 
 Rverfilename)); 
   return false; 
 } else {return false; 
  The catch (Exception e) {return false; }///<summary>///Check for legitimate upload files///</summary>///<param name= "_fileext" ></param>///&L  t;returns></returns> private bool Checkfileext (string _fileext) {string[] Allowext = new string[] {". gif", 
  ". jpg", ". jpeg"}; 
  for (int i = 0; i < allowext.length i++) {if (allowext[i] = = _fileext) {return true;} 
 
return false; 
}//Generate random Number file name public static string GetFileName () {Random rd = new Random ();  StringBuilder serial = new StringBuilder (); Serial. 
  Append (DateTime.Now.ToString ("YYYYMMDDHHMMSSFF")); Serial. Append (Rd. Next (0, 999999). 
  ToString ()); return serial. 
 
ToString ();  }

The above is a small series for everyone to bring the Ajax implementation of the picture preview and upload and generate thumbnails of the entire content of the method, I hope to help you, a lot of support cloud Habitat Community ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.