Go File Upload

Source: Internet
Author: User

Package Mainimport ("FMT"    "io"    "Io/ioutil"    "Log"    "net/http"    "OS"    "reflect")Const(Upload_dir="./uploads") Func Uploadhandler (w http. Responsewriter, R*http. Request) {ifR.method = ="GET"{io. WriteString (W," ""+"enctype=\ "Multipart/form-data\" >"+"Choose an image to upload: <input name=\ "image\" type=\ "file\"/>"+"<input type=\ "submit\" value=\ "upload\"/>"+"</form>")        return    }    ifR.method = ="POST"{F, H, err:= R.formfile ("Image")        ifErr! =Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)return} filename:=H.filename FMT. Println ("FileName:", filename) defer f.close ()//file stream handleT, err:= OS. Create (Upload_dir +"/"+filename) fmt. Println ("filepath:", upload_dir+"/"+filename)ifErr! =Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)return} defer t.close ()//Close the temp file handle        if_, Err: = Io. Copy (T, f); Err! =Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)return} http. Redirect (W, R,"/view?id="+filename, http. Statusfound)}}func Viewhandler (w http. Responsewriter, R*http. Request) {imageId:= R.formvalue ("ID") ImagePath:= Upload_dir +"/"+imageIdifexists: = Isexists (ImagePath);!exists {http. NotFound (W, R)return} w.header (). Set ("Content-type","Image")//HTTP response header output formathttp. Servefile (W, R, ImagePath)}func isexists (Pathstring)BOOL{_, Err:=OS. Stat (PATH)ifErr = =Nil {return true    }    returnOS. Isexist (Err)}func Listhandler (w http. Responsewriter, R*http. Request) {Fileinfoarr, err:= Ioutil. ReadDir ("./uploads")    ifErr! =Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)return    }    varListhtmlstring     for_, FileInfo: =range Fileinfoarr {imgid:=Fileinfo.name FMT. Println ("Type:", reflect. TypeOf (Imgid)) listhtml+="<li><a href=\ "/view?id="+ imgid () +"\ ">"+ imgid () +"</a></li>"} io. WriteString (W,""+listhtml+"</ol></body>")}func init () {//main function before executingFmt. Println ("init-----")}func Safehandler (fn http. Handlerfunc) http. Handlerfunc {//Handling of exceptions    returnFunc (w http. Responsewriter, R *http. Request) {defer func () {ifE, OK: =recover (). (error); OK {http. Error (W, err. Error (), HTTP. Statusinternalservererror) log. Println ("warn:panic in%v-%v", FN, e) log. Println (string(Debug. Stack ()))}} () fn (W, R) }}//working with Static resourcesFunc Staticdirhandler (Mux *http. Servemux, Prefixstring, Staticdirstring, flagsint) {Mux. Handlefunc (Prefix, func (w http. Responsewriter, R*http. Request) {file:= Staticdir + R.url. Path[len (prefix)-1:]        if(Flags & listdir) = =0 {            ifexists: = isexists (file);!exists {http. NotFound (W, R)return}} http. Servefile (W, R, file)})}func Main () {mux:=http. Newservemux () Staticdirhandler (MUX,"/assets/","./public",0) http. Handlefunc ("/", Safehandler (listhandler)) http. Handlefunc ("/view", Safehandler (viewhandler)) http. Handlefunc ("/upload", Safehandler (Uploadhandler)) Err:= http. Listenandserve (": 8080", nil)ifErr! =Nil {log. Fatal ("Listenandserve:", Err. Error ())}}

Go File Upload

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.