Golang Implement image upload

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. # # Golang Implementation image upload this code for the use of Beego to achieve front-end image upload. Words don't say much, directly on the code. # # # # 1. Front-end Code HTML code: ~ ~ ~ <div class= "col-5 f-l text Text-r" > background (required):</div> <div class= "Img-box" > < label> <span class= "copy-btn hui-iconfont" >& #xe679;</span> <input type= "file" class= "Up-file" > </label> </div> <div class= "Img-file col-offset-5" > </div>~~~js code: A. Read the image code for display on the page. ~~~javascript//Read Picture function loadimg () {//Get file var = $ (". Up-file") [0].files[0];//Create object to read file var reader = new Filereade R (); Create file read related variables var imgfile; Set event reader.onload=function for file read successfully (e) {var e=window.event| | E Imgfile = E.target.result; Console.log (Imgfile); $ (". Img-file"). CSS ({' Background ': "url (" +imgfile+ ")"} "); Isimg (); }; Formally read file reader.readasdataurl (files);} ~~~b. Verify that there is a picture present ~~~javascript//whether there is a picture validation function isimg () {var img= $ (". Img-file"). CSS (' background-image '); Img.indexof ("Data:image") ==-1&&img.indexof (". jpg") ==-1) {$ (". Mess"). HTML ("Add background picture"). CSS ("opacity",1); return false; } else{$ (". Mess"). CSS ("opacity", 0). html (""); return true; }}~~~c. Submit the upload, the image is Base64 encoded to the backend ~~~javascriptfunction AddData () {var url=$ (". Img-file"). CSS ("Background-image"); var data1=[{"name": "url", "Value": url}]; $.ajax ({url: "/commmethod/method/uploadimg", Data:data1, type: "Post", ContentType: "Application/json", Success: function (RESP) {...}}); ~~~#### 2. Backend Code ~~~gofunc (this *commmethodcontroller) uploadimg () {fileurl: = this. GetString ("url") Dataarr: = Strings. Split (FileURL, ",")//Remove wrapper, get to base64 encoded IMGBASE64: = Dataarr[1][:len (Dataarr[1])-2]//base64 transcode IMGs, err: = base64. Stdencoding.decodestring (IMGBASE64) if err! = Nil {Beego. Error ("Base64 decode Error:", err)}timenow: = time. Now (). Unix () file, err: = OS. OpenFile ("./static/img/" +strconv. Formatint (TimeNow, +) + ". jpg", OS. O_create|os. O_wronly, 0644) if err! = Nil {Beego. Debug ("Create File Error:", err)}w: = Bufio. Newwriter (file)//Create New Writer Object _, Err3: = W.writestring (String (IMGs)) if ERR3! = nil {Beego. Error ("Write ErroR: ", ERR3)}w.flush () defer file. Close () Imgname: = StrConv. Formatint (TimeNow) + ". jpg" T: = struct {ImageName string ' JSON: "ImageName" '}{imgname}this. data["json"] = tthis. Servejson ()}/*** This code is mainly used to edit the picture, delete the original picture * Determine if the file exists return true does not exist return false */func checkfileisexist (filename string) bool {var ex ist = Trueif _, Err: = OS. Stat (filename); Os. Isnotexist (err) {exist = False}return exist}~~~ The demo uses native JS and the image is transmitted via Base64 encoding. > If a small partner disagrees with the code or advises, please follow the "today's headline" Account "<font color=red> programming Practitioner </font>". We discuss together, study together, welcome harassment 1032 reads  
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.