This code is to use beego to implement front-end and back-end image upload. Without further ado, just upload the code.
1. Front-end code
html code:
<div class="col-5 f-l text text-r">Background image(must):</div> <div class="img-box"> <label> <span class="copy-btn Hui-iconfont"></span> <input type="file" class="up-file"> </label> </div> <div class="img-file col-offset-5"> </div>
Code
a. Read the image code to display it on the page
//Read the picturefunction loadImg(){ //Get the file var file = $(".up-file")[0].files[0]; //Create an object to read the file var reader = new FileReader(); //Create file to read related variables var imgFile; //Set events for file reading successfully =function(e) { var e=||e; imgFile = ; (imgFile); $(".img-file").css({'background':"url("+imgFile+")"}); isimg(); }; //Officially read the file (file); }
b. Verify whether there is an image
//Is there any image verificationfunction isimg(){ var img= $(".img-file").css('background-image'); if(("data:image")==-1&&(".jpg")==-1){ $(".mess").html("Please add background image").css("opacity",1); return false; } else{ $(".mess").css("opacity",0).html(""); return true; } }
c. Submit upload, and pass the image to the backend in base64 encoding
function 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){ ...... } }); }
3. Backend code
func (this *CommMethodController) UploadImg() { fileurl := ("url") DataArr := (fileurl, ",") //Remove the packaging and get the base64 encoding imgBase64 := DataArr[1][:len(DataArr[1])-2] //base64 transcoding imgs, err := (imgBase64) if err != nil { ("base64 decode error:", err) } timenow := ().Unix() file, err := ("./static/img/"+(timenow, 10)+".jpg", os.O_CREATE|os.O_WRONLY, 0644) if err != nil { ("create file error:", err) } w := (file) //Create a new Writer object _, err3 := (string(imgs)) if err3 != nil { ("write error:", err3) } () defer () imgname := (timenow, 10) + ".jpg" t := struct { ImageName string `json:"imagename"` }{imgname} ["json"] = t () } /** *This code is mainly used to delete the original picture when editing pictures * Determine whether the file exists. Return true. If it does not exist, return false. */ func checkFileIsExist(filename string) bool { var exist = true if _, err := (filename); (err) { exist = false } return exist }
This is the article about this example code for Golang to implement the image upload function. For more related Golang image upload content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!