• upload.go


    package api

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

    func Upload(host string, port int, dst string, src string) (err error) {
        fi, err := os.Stat(src)
        if os.IsNotExist(err) {
            return err
        }
        if fi.IsDir() {
            return fmt.Errorf("can't upload a directry: %s", src)
        }

        if dst[len(dst) - 1] == '/' {
            dst += filepath.Base(src)
        }

        var url string
        if dst[0] == '/' {
            url = fmt.Sprintf("http://%s:%d%s", host, port, dst)
        }else {
            url = fmt.Sprintf("http://%s:%d/%s", host, port, dst)
        }
        file, _ := os.Open(src)

        body := new(bytes.Buffer)
        mPart := multipart.NewWriter(body)

        filePart, err := mPart.CreateFormFile("file", filepath.Base(dst))
        if err != nil {
            return
        }

        _, err = io.Copy(filePart, file)
        if err != nil {
            return
        }

        mPart.Close()

        req, err := http.NewRequest(http.MethodPost, url, body)
        if err != nil {
            return
        }
        req.Header.Set("Content-Type", mPart.FormDataContentType())

        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            return
        }
        defer resp.Body.Close()

        if resp.StatusCode != http.StatusCreated {
            body, _ := ioutil.ReadAll(resp.Body)
            err = errors.New(fmt.Sprintf("%d != http.StatusCreated  body: %s", resp.StatusCode, body))
        }
        return
    }

  • 相关阅读:
    第三方模块加载时出现XXX运行 提示错误:无法加载文件 C:UsersgxfAppDataRoaming pmXXX.ps1,因为在此系统上禁止运行脚本。
    node模块化
    前端面试集锦
    将字符转换成驼峰表示法
    JavaScript数据处理
    大数据基础整合
    移动端网页特效
    本地存储
    DOM重点核心
    触发器SQL
  • 原文地址:https://www.cnblogs.com/zhangboyu/p/7461590.html
Copyright © 2020-2023  润新知