zoukankan      html  css  js  c++  java
  • upload.go

    package api

    import (
        "os"
        "bytes"
        "mime/multipart"
        "path/filepath"
        "io"
        "net/http"
        "errors"
        "fmt"
        "io/ioutil"
    )
    //上传文件到指定的位置
    func Upload(host string, port int, vid uint64, fid uint64, filePath string, fileName string) (err error) {
        if fileName == "" {
            fileName = filepath.Base(filePath)
        }

        url := fmt.Sprintf("http://%s:%d/%d/%d/%s", host, port, vid, fid, fileName)
        file, err := os.Open(filePath)
        if os.IsNotExist(err) {
            return
        }

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

        filePart, err := mPart.CreateFormFile("file", fileName)
        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
    }

  • 相关阅读:
    好用的QT连接
    c指针点滴-指针与类型
    c指针点滴5-指针变量计算
    c指针点滴4-指针的值
    c指针点滴三(指针运算)
    c语言指针点滴1
    c指针点滴2之比大小
    c指针点滴1
    linux安装redis
    支付宝支付接口流程
  • 原文地址:https://www.cnblogs.com/zhangboyu/p/7461607.html
Copyright © 2011-2022 走看看