goLang 上传文件 以及 获取文件的名称、前缀、后缀

一、文件上传

package main

import (
  "bytes"
  "fmt"
  "io"
  "io/ioutil"
  "mime/multipart"
  "net/http"
  "os"
  "path"
)

func postFile(filename string, targetUrl string) error {
  bodyBuf := &bytes.Buffer{}
  bodyWriter := multipart.NewWriter(bodyBuf)

  // 关键的一步操作
  fileWriter, err := bodyWriter.CreateFormFile("file", path.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()

  resp, err := http.Post(targetUrl, contentType, bodyBuf)
  if err != nil {
    return err
  }
  defer r

你可能感兴趣的:(goLang,golang)