golang 后端上传文件

//上传图片方法   参数为文件名
func postFile(filename string) (error, string) {
	bodyBuf := &bytes.Buffer{}
	bodyWriter := multipart.NewWriter(bodyBuf)
	//"file" 为接收时定义的参数名
	fileWriter, err := bodyWriter.CreateFormFile("file", filepath.Base(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()
    //conf.UploadString:上传路径接口 ,向接收端发请求
	resp, err := http.Post(conf.UploadString, contentType, bodyBuf)
    //打印接口返回信息
	fmt.Println(resp)
	if err != nil {
		log.Println("上传错误信息:", err)
		return err, ""
	}
	defer resp.Body.Close()
	resp_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err, ""
	}
    //根据实际需要,返回相应的信息
	return nil, string(resp_body)
}

 

你可能感兴趣的:(go)