V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
v2016
V2EX  ›  问与答

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

  •  
  •   v2016 · 2022-10-23 20:04:53 +08:00 · 1014 次点击
    这是一个创建于 522 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    5 条回复    2022-10-24 10:17:33 +08:00
    insert000
        1
    insert000  
       2022-10-23 20:07:10 +08:00
    POST 请求 :file_get_contents('php://input');
    v2016
        2
    v2016  
    OP
       2022-10-23 20:11:41 +08:00
    @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  
       2022-10-23 20:56:30 +08:00
    https://www.php.net/manual/en/wrappers.php.php

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

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

    你要内容直接放 body 体就不要用 multipart/form-data
    Great233
        5
    Great233  
       2022-10-24 10:17:33 +08:00
    试了下 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 接收
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1191 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 23:18 · PVG 07:18 · LAX 16:18 · JFK 19:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.