package NiuPicT

/**
@author: sre
@date: 2022/8/17 0017
@desc: upload img to niupic
**/

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "mime/multipart"
    "net/http"
    "os"
    "path/filepath"
    "testing"
)

func TestUpload(t *testing.T) {
    body, err := upload("D:\\Desktop\\mow\\test.JPG")
    if err != nil {
        fmt.Println(err)
        return
    }
    var result niupicRes
    _ = json.Unmarshal(body, &result)
    fmt.Println(result.Data)
}

type niupicRes struct {
    Status string `json:"status"`
    Code   int    `json:"code"`
    Data   string `json:"data"`
    Msg    string `json:"msg"`
}

func upload(filePath string) ([]byte, error) {

    url := "https://www.niupic.com/api/upload"
    method := "POST"

    payload := &bytes.Buffer{}
    writer := multipart.NewWriter(payload)
    file, errFile1 := os.Open(filePath)
    defer file.Close()
    part1,
        errFile1 := writer.CreateFormFile("file", filepath.Base(filePath))
    _, errFile1 = io.Copy(part1, file)
    if errFile1 != nil {
        fmt.Println(errFile1)
        return nil, errFile1
    }
    err := writer.Close()
    if err != nil {
        fmt.Println(err)
        return nil, err
    }

    client := &http.Client{}
    req, err := http.NewRequest(method, url, payload)

    if err != nil {
        fmt.Println(err)
        return nil, err
    }
    req.Header.Add("authority", "www.niupic.com")
    req.Header.Add("accept", "application/json")
    req.Header.Add("accept-language", "zh-CN,zh;q=0.9")
    req.Header.Add("cache-control", "no-cache")
    req.Header.Add("content-type", "multipart/form-data; boundary=----WebKitFormBoundaryaMYCTFSFkhzG1SCm")
    req.Header.Add("cookie", "ua_lang=zh-cn; PHPSESSID=e5a6d75fd9cc2f05ab0bfc22808f34fc; PHPSESSID=e5a6d75fd9cc2f05ab0bfc22808f34fc; ua_lang=zh-cn")
    req.Header.Add("dnt", "1")
    req.Header.Add("origin", "https://www.niupic.com")
    req.Header.Add("referer", "https://www.niupic.com/")
    req.Header.Add("sec-ch-ua", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"")
    req.Header.Add("sec-ch-ua-mobile", "?0")
    req.Header.Add("sec-ch-ua-platform", "\"Windows\"")
    req.Header.Add("sec-fetch-dest", "empty")
    req.Header.Add("sec-fetch-mode", "cors")
    req.Header.Add("sec-fetch-site", "same-origin")
    req.Header.Add("'user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36")
    req.Header.Add("x-requested-with", "XMLHttpRequest")

    req.Header.Set("Content-Type", writer.FormDataContentType())
    res, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return nil, err
    }
    defer res.Body.Close()

    body, err := io.ReadAll(res.Body)
    if err != nil {
        fmt.Println(err)
        return nil, err
    }
    return body, nil
}

发表回复

您的电子邮箱地址不会被公开。

Captcha Code