AJAX allows you to preview and upload images and generate thumbnails,

Source: Internet
Author: User

AJAX allows you to preview and upload images and generate thumbnails,

To implement the function, you can preview an image when uploading it. Because there are other texts, you can not only upload the image, but save it together with other texts. Of course, you can upload the image first, then, write the path and other text into the database. At the same time, a thumbnail is generated for the image. Now, only the Image Upload method is written. The text can be directly transferred to parameters in ajax. to upload multiple images, you can modify it.

I learned from the online materials and wrote it myself. I don't need to add a new page. I just want to add it on one page.

JS Code:

// Ajax stores data. This function is implemented in the background method to SaveData () {filename = document. getElementById ("idFile "). value; result = test_test_aspx.SaveData (filename ). value; if (result) {alert ("saved successfully! ");} Return false;} // implement the 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; 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 front-end code:

<Div class = "cbs"> <div class = "l"> <label> image: </label> </div> <input id = "idFile" name = "pic" type = "file" runat = "server" onchange = "FileChange (this. value); "/> </div> <div class =" cbs "> <div class =" l "> <label> preview: </label> </div>  // This is mainly used to display the image during viewing. Because the above (idImg) is added with runat =" server ", an error is returned, leave a message if you have a good method. </div>

The AJAX method is as follows:

[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 be saved FileInfo file = new FileInfo (fileNamePath); // get the file extension string fileNameExt = file. extension; // verify the valid file if (CheckFileExt (fileNameExt) {// generate the random file name to be saved string fileName = GetFileName () + fileNameExt; // check whether the saved path has/end if (sSavePath. endsWith ("/") = false) sSavePath = sSavePath + "/"; // return by date Class to save string datePath = DateTime. now. toString ("yyyyMM") + "/" + DateTime. now. toString ("dd") + "/"; if (true) {sSavePath + = datePath;} // obtain the file path to be saved: serverFileName = sSavePath + fileName; // physical full path string toFileFullPath = HttpContext. current. server. mapPath (sSavePath); // check whether this path exists. if (! Directory. exists (toFileFullPath) {Directory. createDirectory (toFileFullPath);} // complete file name to be saved string toFile = toFileFullPath + fileName; // create a WebClient instance WebClient myWebClient = new WebClient (); // set windows Network Security Authentication myWebClient. credentials = CredentialCache. defaultCredentials; // file to be uploaded FileStream fs = new FileStream (fileNamePath, FileMode. open, FileAccess. read); // FileStream fs = OpenFile (); BinaryReader r = new BinaryReader (fs); // you can use the following format to use UploadFile: // 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 source image try {// The Source image loads using (System. drawing. image sourceImage = System. drawing. image. fromFile (System. web. httpContext. current. server. mapPath (serverFileName) {// source image width and height int width = sourceImage. width; int height = sourceImage. height; int smallWidth; int smallHeight; // obtain the size of the first drawing image (compare the width of the source image/the width of the thumbnail and the Height of the source image/the Height of the thumbnail) if (decimal) width)/height <= (decimal) intThumbWidth)/intThumbHeight) {smallWidth = intThumbWidth; smallHeight = intThumbWidth * height/width ;} else {smallWidth = intThumbHeight * width/height; smallHeight = intThumbHeight;} // determines whether the thumbnail has int file_append = 0 in the same name file in the current folder; 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;} // the absolute path string smallImagePath = System. web. httpContext. current. server. mapPath (sSavePath) + sThumbFile; // create a new graphic board and draw the original image using (System. drawing. image bitmap = new System. drawing. bitmap (smallWidth, smallHeight) {// draw the intermediate figure using (System. drawing. graphics g = System. drawing. graphics. fromImage (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 graphic board and draw the intermediate image using (System. drawing. image bitmap1 = new System. drawing. bitmap (intThumbWidth, intThumbHeight) {// draw the thumbnail using (System. drawing. graphics g = System. drawing. graphics. fromImage (bitmap1) {// HD, smooth g. interpolationMode = 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 ;}}}} catch {// delete System if an error occurs. IO. file. delete (System. web. httpContext. current. server. mapPath (serverFileName); return false ;}} else {return false ;}} catch (Exception e) {return false ;}} /// <summary> /// check whether the file is uploaded properly /// </summary> /// <param name = "_ fileExt"> </param>/ // <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 the 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 all the content of the AJAX Method for you to preview and upload images and generate thumbnails. I hope it will be helpful to you and support more help ~

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.