Go Photo Upload

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Use the go language to implement the image upload function, server and client source code.

Server-side code:

Uploadfile_server.gopackage Mainimport (//"CRYPTO/MD5" "FMT"//"html/template" "io" "Log" "Net/http" "OS"//"StrConv" "Time")//check whether the directory exists func checkfileisexist (filename string) bool {var exist = Trueif _, Err: = OS. Stat (filename); Os. Isnotexist (Err) {FMT. Print (filename + "not exist") exist = False}return Exist}func Main () {http. Handlefunc ("/upload", upload) Err: = http. Listenandserve (": 9090", nil)//Set the listening port if err! = Nil {log. Fatal ("Listenandserve:", err)}log. Println ("success!")} Handle the/upload logical func upload (w http. Responsewriter, R *http. Request) {fmt. Println ("Method:", R.method)//Get the requested method/*if R.method = = "Get" {crutime: = time. Now (). Unix () H: = MD5. New () Io. WriteString (H, StrConv. Formatint (Crutime, Ten)) token: = Fmt. Sprintf ("%x", H.sum (nil)) T, _: = template. Parsefiles ("Upload.gtpl") T.execute (W, token)} else */fmt.  Println (r) If R.method = = "POST" {r.parsemultipartform (<<) file, handler, err: = R.formfile ("UploadFile") If err ! = Nil {fmt. PRINTLN (Err) return}defer file. Close () fmt. fprintf (W,"%v", handler. Header)//bool_fileexist: = Checkfileisexist ("./test") fmt. Println ("Check file 1-----------------") fmt. Println ("-------------------------bool_fileexist:", bool_fileexist) if bool_fileexist {//If the folder exists//f, err1 = os. OpenFile (filename, os. O_append, 0666)//Open file F, err: = OS. OpenFile ("./test/" +handler. Filename, OS. O_wronly|os. O_create, 0666) if err! = Nil {fmt. PRINTLN (Err) return}defer f.close () io. Copy (f, file) Fmt. Println ("folder exists")} else {//The folder is not present when you first create a folder and then upload err1: = os. Mkdir ("./test", Os. Modeperm)//Create folder if ERR1! = nil {fmt. PRINTLN (Err) return}fmt. Println ("folder does not exist") fmt. Println ("Folder creation succeeded! ") F, err: = OS. OpenFile ("./test/" +handler. Filename, OS. O_wronly|os. O_create, 0666) if err! = Nil {fmt. PRINTLN (Err) return}defer f.close () io. Copy (f, File)}}


Client code:

Uploadfile_client.gopackage mainimport ("bytes" "FMT" "io" "io/ioutil" "Mime/multipart" "Nettp" "OS") Func Postfile ( FileName string, TargetUrl string) error {bodybuf: = &bytes. Buffer{}bodywriter: = multipart. Newwriter (BODYBUF)//Key step operation FileWriter, err: = Bodywriter.createformfile ("UploadFile", filename) if err! = Nil {fmt. PRINTLN ("Error writing to buffer") return err}//Open file handle operation FH, err: = OS. Open (filename) if err! = Nil {fmt. PRINTLN ("Error opening file") return Err}defer FH. Close ()//iocopy_, err = io. Copy (FileWriter, FH) if err! = Nil {return Err}contenttype: = Bodywriter.formdatacontenttype () bodywriter.close () RESP, ERR: = http. Post (TargetUrl, ContentType, Bodybuf) fmt. Println (BODYBUF) if err! = Nil {return Err}defer resp. Body.close () resp_body, err: = Ioutil. ReadAll (resp. Body) If err! = Nil {return err}fmt. Println (resp. Status) fmt. Println (String (resp_body)) return nil}//sample Usagefunc main () {target_url: = "http://xxx.xxx.xxx.xxx:9090/upload"// Here is your own IP address filename: = "image2.jpg" postfile (filename, Target_url)} 




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.