V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
v2016
V2EX  ›  问与答

如何实现 golang 发送文件 PHP 接收文件

  •  
  •   v2016 · Oct 23, 2022 · 1710 views
    This topic created in 1282 days ago, the information mentioned may be changed or developed.

    找了下 golang 发送文件的例子都是二进制流,都试了下,发现 php 接收不到

    5 replies    2022-10-24 10:17:33 +08:00
    insert000
        1
    insert000  
       Oct 23, 2022
    POST 请求 :file_get_contents('php://input');
    v2016
        2
    v2016  
    OP
       Oct 23, 2022
    @insert000
    我 golang 这样写,php 端使用'php://input'接收到的依旧为空
    func postFile(){
    //这是一个 Post 参数会被返回的地址
    strinUrl:="http://localhost:8080/aaa"
    byte,err:=ioutil.ReadFile("post.txt")
    resopne,err :=http.Post(strinUrl,"multipart/form-data",bytes.NewReader(byte))
    if err !=nil {
    fmt.Println("err=",err)
    }
    defer func() {
    resopne.Body.Close()
    fmt.Println("finish")
    }()
    body,err:=ioutil.ReadAll(resopne.Body)
    if err!=nil {
    fmt.Println(" post err=",err)
    }
    fmt.Println(string(body))
    }
    eason1874
        3
    eason1874  
       Oct 23, 2022
    https://www.php.net/manual/en/wrappers.php.php

    php://input is not available with enctype="multipart/form-data". 是不是这个原因?
    iyaozhen
        4
    iyaozhen  
       Oct 23, 2022
    @v2016 你这个提交的不符合 http 规范吧

    https://juejin.cn/post/6996901713122852895 四种常见的 POST 提交数据方式

    你要内容直接放 body 体就不要用 multipart/form-data
    Great233
        5
    Great233  
       Oct 24, 2022
    试了下 go1.19.2 PHP8.1 ,按照你的写法 PHP 直接 `file_get_contents('php://input');` 是可以获取到内容的,但是 PHP 报了一条 Warning:Missing boundary in multipart/form-data POST data in Unknown on line 0 。

    对于你的问题,go 可以用 `mime/multipart` 包来组装 post body:
    ```
    var buf bytes.Buffer
    w := multipart.NewWriter(&buf)
    defer w.Close()
    fileWriter, _ := w.CreateFormFile("file", "./post.txt")
    fd, _ := os.Open("./post.txt")
    defer fd.Close()
    io.Copy(fileWriter, fd)
    resopne, err := http.Post(strinUrl, w.FormDataContentType(), &buf)
    ```
    PHP 使用 $_FILES 接收
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1475 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 17:06 · PVG 01:06 · LAX 10:06 · JFK 13:06
    ♥ Do have faith in what you're doing.