Localresizeimg+asp.net implementation of image compression upload

Source: Internet
Author: User

Recent project encountered mobile side upload image file, but the Internet is basically SWF mode upload. Localresizeimg is a good fit.

Because the niche is not to learn PHP, online demo is basically PHP, their own groping to make a asp.net version of, hope to help users.


The first is HTML:

  <a href= "javascript:;" class= "A-upload" >
                        <input type= "file" id= "Idcard_pic" name= "Idcard_pic" accept= " Image/jpeg "/>
                            <span> click here to upload file </span>
                    </a>
Here are the three hidden fields where the path is stored
<input type= "hidden" id= hididcard "name=" Hididcard "value=" "/> <input type=" hidden "id=" Hidphoto "Name=
                "Hidphoto" value= "/> <input type=" hidden "id=" Hiddiploma "name=" Hiddiploma "value=" "/>"
                

Next is the most important JS code, in order to facilitate directly in its demo JS inside done.

Input0.onchange = function () {//You can also pass in the picture path: Lrz (' ... /demo.jpg ', ... lrz (This.files[0], {width:800,quality:0.7}, function (results) {//All the data you need is here, you can use a string
            The form of the transfer Base64 to the service side of the dump as a picture.
            Console.log (results);    settimeout (function () {//if (Results.base64.length > 5242880)//{//
                $.dialog.tips ("Upload failed, file too large, please upload picture less than 5M", 1, "32x32/succ.png", function () {//Location.reload ();
                //    });
                //Send To Back-end var xhr = new XMLHttpRequest ();
                    var data = {base64:results.base64, size:results.base64.length,//checksum to prevent incomplete reception

                Name:results.origin.name}; Xhr.open (' POST ', '.. /..
                /upload.ashx?action=uploadimg ', true);
             Xhr.setrequestheader (' Content-type ', ' Application/json; Charset=utf-8 ');   Xhr.onreadystatechange = function () {if (xhr.readystate = = 4 && xhr.status = = 200) { if (xhr.response!= 0) {//sessionstorage.setitem ("Idcard", Xhr.response
                            );
                            Document.cookie = "idcard=" + xhr.response;
                            var index= xhr.response.toString (). IndexOf (' & ');
                            $ ("#hididcard"). Val (xhr.response.substring (0, index));
                        $ (input0). Parent (' a '). Find (' span '). HTML (xhr.response.toString (). substr (index + 1)); }//result.error//?
                    Alert (' Server-side error, failed to save picture ')//: Demo_report (' Server-side real-store picture ', Result.src, result.size);

                }
                }; Xhr.send (json.stringify (data));
        Send base64}, 100);
    }); };

Results.base64 encapsulates the image information that can be used to get compressed picture information

Localresizeimg There are a lot of settings picture fields that I don't say much

In data, you can send results.base64 other information to the background


The data is sent to the back end through XMLHttpRequest, and the file is saved by a general handler at the back end.

The following is the general handler upload.ashx part of the code:

<summary>///upload picture///</summary>///<param name= "context" ></param> public void Uploadimg (HttpContext context) {//Get Base64 encoding dictionary<string, OBJ
            ect> Dicparameter = getparameter (context); String base64 = dicparameter["base64"]. ToString ();//base64 encoded int size = Convert.ToInt32 (dicparameter["size"). ToString ());//base64 size string filename = dicparameter["name"]. ToString ();//the original filename base64 = base64. Replace ("", "+");/fix base64 + to a space string uid = context. request.querystring["UID"];//get the user id uid = UID. Substring (0, UID. LENGTH-1);/Do not know why, after the UID has a space string type = context. request.querystring["type"];//get the Upload file type string basepath= "/uploads/";//basic path//string FilePath = Comm Onutil.getmappath (BasePath);//folder path string name = UID + "_" + Type + "_" +filename;//File name uploaded to server/ /checkWhether an uploaded physical path exists or does not exist creates an if (!
            Directory.Exists (FilePath)) {directory.createdirectory (FilePath); foreach (String file in Directory.enumeratefiles (FilePath))//delete uploaded pictures {if (file . Substring (file. LastIndexOf ("\") +1).
                StartsWith (uid + "_" + Type + "_")) {File.delete (File); } try {Base64stringtoimage (base64). Substring (base64.
                 LastIndexOf (",") + 1), FilePath + name);//Picture save string Dese = Desencrypt.encrypt (basepath + name);//Encrypt data Context. Response.Write (dese+ "&" +filename);//return Encrypted file path and original filename} catch {Conte Xt.
            Response.Write (0); } context.
        Response.End (); }

base64 = base64. Replace ("", "+"); Do not know why Base64 ' + ' turned into a space, waste my nearly a day time. If we do not have such a situation, we can omit it.

        <summary>
        ///Get parameters
        ///</summary>
        ///<param name= "context" ></param>
        // /<returns></returns>
        private dictionary<string, object> GetParameter (HttpContext context)
        {
            StreamReader reader = new StreamReader (context. Request.inputstream);
            String Strjson = Httputility.urldecode (reader. ReadToEnd ());
            JavaScriptSerializer JSS = new JavaScriptSerializer ();
            Deserializes the JSON string into a Dictionary object
            dictionary<string, object> dicparameter = JSS. Deserialize<dictionary<string, object>> (Strjson);
            return dicparameter;
        }


Background through the GetParameter method to get the data passed over


Save Base64 encoded to picture file
        protected void Base64stringtoimage (String strbase64,string filepath)
        {
            try
            {
                byte[] arr = convert.frombase64string (strbase64);
                MemoryStream ms = new MemoryStream (arr);
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap (ms);
                Bmp. Dispose ();
                Bmp. Save (filepath, System.Drawing.Imaging.ImageFormat.Jpeg);  
                Ms. Close ();
            }
            catch (Exception ex)
            {
            }
        }

The file name rules for uploading to the server are: uid_type_ Original file name

Upload the file path to the server do your own hands and feet, this does not say much.

I am the upload file path after the encryption operation, and then returned to the foreground is a string of encoding is not the original path of the strings. At the same time, the original file name returned to the front desk for easy use.

After the picture is saved, the name of the uploaded file is displayed, indicating that the upload is complete.


Disadvantage: No upload file size limit is implemented


I'm using this LocalResizeIMG3

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.