Go图片上传

来源:转载

使用Go语言实现图片上传功能,服务器及客户端的源代码。

服务器端代码:

// uploadfile_server.gopackage mainimport (//"crypto/md5""fmt"//"html/template""io""log""net/http""os"//"strconv"//"time")//检查目录是否存在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) //设置监听的端口if err != nil {log.Fatal("ListenAndServe: ", err)}log.Println("success!")}// 处理/upload 逻辑func upload(w http.ResponseWriter, r *http.Request) {fmt.Println("method:", r.Method) //获取请求的方法/*if r.Method == "GET" {crutime := time.Now().Unix()h := md5.New()io.WriteString(h, strconv.FormatInt(crutime, 10))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(32 << 20)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 { //如果文件夹存在//f, err1 = os.OpenFile(filename, os.O_APPEND, 0666) //打开文件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("文件夹存在")} else { //不存在文件夹时 先创建文件夹再上传err1 := os.Mkdir("./test", os.ModePerm) //创建文件夹if err1 != nil {fmt.Println(err)return}fmt.Println("文件夹不存在")fmt.Println("文件夹创建成功!")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)}}}

客户端代码:

// 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)//关键的一步操作fileWriter, err := bodyWriter.CreateFormFile("uploadfile", filename)if err != nil {fmt.Println("error writing to buffer")return err}//打开文件句柄操作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"//此处为自己的ip地址filename := "image2.jpg"postFile(filename, target_url)}

版权声明:本文为博主原创文章,未经博主允许不得转载。

分享给朋友:
您可能感兴趣的文章:
随机阅读: