golang post file to flask server

huangapple go评论86阅读模式
英文:

golang post file to flask server

问题

我试图创建一个应用程序,该应用程序将从页面上的表单发送文件到Golang服务器,然后再将其转发到Flask服务器。

我的Golang服务器代码如下:

func api_upload_model(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(50 << 20)
    file, handler, err := r.FormFile("Model")
    if err != nil {
        fmt.Println("Error Retrieving the File")
        fmt.Println(err)
        return
    }
    fmt.Printf("Uploaded File: %+v\n", handler.Filename)
    fmt.Printf("File Size: %+v\n", handler.Size)
    
    resp, err := http.Post(*在此处输入URL*, "multipart/form-data", file)
    if err != nil {
        fmt.Println("Error Sending the File")
        fmt.Println(err)
        return
    }
    w.Header().Set("Content-Type", "text/html")
    buffer, _ := ioutil.ReadAll(resp.Body)
    _, err = w.Write(buffer)
    if err != nil {
        fmt.Println("Error Sending the File")
        fmt.Println(err)
        return
    }
}

func main() {
    router := chi.NewRouter()
    router.Post("/api/upload_model", api_upload_model)
    http.ListenAndServe(":8080", router)
}

Flask服务器代码如下:

@app.route('/upload_model', methods=['POST'])
def upload_model():
    log("Inference server", "123")
    name = request.args.get('name', None)
    if name is None:
        return "Error: bad request parameters."
    print(str(request))
    if 'file' not in request.files:
        return "No file"
    file = request.files['file']
    if file:
        filename = secure_filename(name)
        file.save(os.path.join("data/models", name))
        return "200"

从Flask服务器收到的内容如下:

<Request 'http://*在此处输入URL*/upload_model?name=1.jpg' [POST]>:

我尝试打印request.files,结果为空。所以,要么Golang服务器没有发送文件,要么Flask服务器没有接收到文件。

Golang服务器打印的结果如下:

Uploaded File: 1.jpg
File Size: 114940

因此,它成功接收到文件。

更新:
我找到了这个答案:https://stackoverflow.com/questions/66591844/how-to-redirect-multipart-post-request-to-a-second-server-in-golang
并按照其中的方法修改了我的Golang服务器代码。现在它不解析文件,而是将整个请求未经修改地发送到Flask服务器。这样更加简单。

英文:

I try to create app which will send file from the form on page to the golang server and it will resend it to flask server.

My golang server:

func api_upload_model(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(50 &lt;&lt; 20)
    file, handler, err := r.FormFile(&quot;Model&quot;)
    if err != nil {
        fmt.Println(&quot;Error Retrieving the File&quot;)
        fmt.Println(err)
        return
    }
    fmt.Printf(&quot;Uploaded File: %+v\n&quot;, handler.Filename)
    fmt.Printf(&quot;File Size: %+v\n&quot;, handler.Size)
    
    resp, err := http.Post(*URL here*, &quot;multipart/form-data&quot;, file)
    if err != nil {
        fmt.Println(&quot;Error Sending the File&quot;)
        fmt.Println(err)
        return
    }
    w.Header().Set(&quot;Content-Type&quot;, &quot;text/html&quot;)
    buffer, _ := ioutil.ReadAll(resp.Body)
    _, err = w.Write(buffer)
    if err != nil {
        fmt.Println(&quot;Error Sending the File&quot;)
        fmt.Println(err)
        return
    }
}

func main() {
    router := chi.NewRouter()
    router.Post(&quot;/api/upload_model&quot;, api_upload_model)
    http.ListenAndServe(&quot;:8080&quot;, router)
}

Flask handler:

@app.route(&#39;/upload_model&#39;, methods=[&#39;POST&#39;])
def upload_model():
    log(&quot;Inference server&quot;, &quot;123&quot;)
    name = request.args.get(&#39;name&#39;, None)
    if name is None:
        return &quot;Error: bad request parameters.&quot;
    print(str(request))
    if &#39;file&#39; not in request.files: #I know that I don&#39;t set filename to &#39;file&#39; but request.files is empty anyway
        return &quot;No file&quot;
    file = request.files[&#39;file&#39;]
    if file:
        filename = secure_filename(name)
        file.save(os.path.join(&quot;data/models&quot;, name))
        return &quot;200&quot;

What I get from flask server:

&lt;Request &#39;http://*URL here*/upload_model?name=1.jpg&#39; [POST]&gt;: 

I tried to print request.files: it is empty.
So, golang server doesn't send file or flask server doesn't get it.

Golang prints

Uploaded File: 1.jpg
File Size: 114940

So it recieves file.

UPD:
Found this answer: https://stackoverflow.com/questions/66591844/how-to-redirect-multipart-post-request-to-a-second-server-in-golang
and made my golang server like there. Now it doesn't parse files but sends whole request to flask server unedited. And it is more easy.

答案1

得分: 1

你不能直接将FormFile作为输入传递给POST方法,而是需要创建一个包含文件的多部分对象。

参考示例
https://stackoverflow.com/questions/58105449/how-to-use-multipart-in-golang#58110947

英文:

You cannot directly pass the FormFile as an input to the post method instead you need to create a multipart object that contains the file.

See example
https://stackoverflow.com/questions/58105449/how-to-use-multipart-in-golang#58110947

huangapple
  • 本文由 发表于 2021年9月29日 17:32:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/69373788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定