登录
首页 >  Golang >  Go问答

图像传输失败:无法从URL发送文件到Cloudflare

来源:stackoverflow

时间:2024-02-12 12:09:22 431浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《图像传输失败:无法从URL发送文件到Cloudflare》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我使用的是 google app 引擎,这意味着仅允许通过云存储写入文件。当 api 被调用时,我可以抓取文件并将其存储在谷歌云存储中,没有任何问题。该函数仅返回保存它的 url。 我想获取该图像 url,然后将其发送到 cloudflare 图像,因为它们允许您创建变体。

type imageresult struct {
            result struct {
                id                string    `json:"id"`
                filename          string    `json:"filename"`
                uploaded          time.time `json:"uploaded"`
                requiresignedurls bool      `json:"requiresignedurls"`
                variants          []string  `json:"variants"`
            } `json:"result"`
            resultinfo interface{}   `json:"result_info"`
            success    bool          `json:"success"`
            errors     []interface{} `json:"errors"`
            messages   []interface{} `json:"messages"`
}

以上是表示 cloudflare 响应的结构。下面是直接获取 google 云存储 url 并“下载”它,然后将其发送到 cloudflare 的函数。

func cloudflareurl(url, filename string) (*imageresult, error) {
    cloudflareurl := "https://api.cloudflare.com/client/v4/accounts/" + konsts.cloudflareacc + "/images/v1"
    cloudflareauth := "bearer " + konsts.cloudflareapi
    r, err := http.get(url)
    if err != nil {
        return nil, errors.wrap(err, "couldn't get the file")
    }
    if r.statuscode != 200 {
        return nil, errors.new("couldn't get the file")
    }
    defer r.body.close()
    buff := make([]byte, 4096)
    _, err = r.body.read(buff)

    req, err := http.newrequest("post", cloudflareurl, bytes.newreader(buff))
    if err != nil {
        return nil, errors.wrap(err, "couldn't create the request")
    }
    req.header.set("content-type", "multipart/form-data")
    req.header.set("authorization", cloudflareauth)

    client := &http.client{}
    resp, err := client.do(req)
    if err != nil {
        return nil, errors.wrap(err, "couldn't send the request")
    }

    var result imageresult
    bodi := &bytes.buffer{}
    _, err = bodi.readfrom(resp.body)
    if err != nil {
        return nil, errors.wrap(err, "couldn't read the response body")
    }
    resp.body.close()
    err = json.unmarshal(bodi.bytes(), &result)
    if err != nil {
        return nil, errors.wrap(err, "couldn't unmarshal the response body")
    }
    return &result, nil
}

这是错误消息; 寻找值开头的字符“e”无效 无法解组响应正文

现在,在我的笔记本电脑上,如果我在发送文件后运行 api 服务器,我可以将其保存在磁盘上,打开它并毫无问题地发送到 cloudflare。这是代码

func cloudflarefile(params map[string]string, paramname, path string) (*imageresult, error) {
    file, err := os.open(path)
    if err != nil {
        return nil, err
    }
    defer file.close()

    body := &bytes.buffer{}
    writer := multipart.newwriter(body)
    part, err := writer.createformfile(paramname, filepath.base(path))
    if err != nil {
        return nil, err
    }
    _, err = io.copy(part, file)

    for key, val := range params {
        _ = writer.writefield(key, val)
    }
    err = writer.close()
    if err != nil {
        return nil, err
    }
    cloudflareurl := "https://api.cloudflare.com/client/v4/accounts/" + konsts.cloudflareacc + "/images/v1"
    cloudflareauth := "bearer " + konsts.cloudflareapi
    req, err := http.newrequest("post", cloudflareurl, body)
    req.header.set("content-type", writer.formdatacontenttype())
    req.header.set("authorization", cloudflareauth)
    var result imageresult
    client := &http.client{}
    resp, err := client.do(req)
    if err != nil {
        return nil, errors.wrap(err, "couldn't send the request")
    } else {
        body := &bytes.buffer{}
        _, err := body.readfrom(resp.body)
        if err != nil {
            return nil, errors.wrap(err, "couldn't read the response body")
        }
        resp.body.close()
        err = json.unmarshal(body.bytes(), &result)
        if err != nil {
            return nil, errors.wrap(err, "couldn't unmarshal the response body")
        }
    }
    return &result, nil
}

我尝试过各种变体,但总是失败。例如;

req, err := http.NewRequest("POST", cloudFlareUrl, r.body)
    if err != nil {
        return nil, errors.Wrap(err, "Couldn't create the request")
    }
    req.Header.Set("Content-Type", "multipart/form-data")
    req.Header.Set("Authorization", cloudFlareAuth)

正确答案


好的,对于其他遇到此问题的人来说。我解决了。

r, err := http.Get(url)
    if err != nil {
        return nil, errors.Wrap(err, "Couldn't get the file")
    }
    if r.StatusCode != 200 {
        return nil, errors.New("Couldn't get the file")
    }
    defer r.Body.Close()
    b := &bytes.Buffer{}
    a := make([]byte, 4096)
    wr := multipart.NewWriter(b)
    part, err := wr.CreateFormFile("file", filename)
    if err != nil {
        return nil, errors.Wrap(err, "Couldn't create the form file")
    }
    _, err = io.CopyBuffer(part, r.Body, a)
    wr.Close()

    req, err := http.NewRequest("POST", cloudFlareUrl, bytes.NewReader(b.Bytes()))
    if err != nil {
        return nil, errors.Wrap(err, "Couldn't create the request")
    }
    // req.Header.Set("Content-Type", "multipart/form-data")
    req.Header.Set("Content-Type", wr.FormDataContentType())
    req.Header.Set("Authorization", cloudFlareAuth)

今天关于《图像传输失败:无法从URL发送文件到Cloudflare》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>