【问题标题】:Not receiving correctly multipart form data with PHP Klein使用 PHP Klein 无法正确接收多部分表单数据
【发布时间】:2021-09-21 14:05:33
【问题描述】:

从我的 reactJS 前端发送到由 Klein 处理的 PHP api 的多部分表单请求接收数据时,我遇到了一个大问题。 我只是尝试用 Javascript 发送这个获取请求

 const data = new FormData();
    data.append('sourceId', sourceId);
    data.append('customerId', customerId);
    const resp = await fetch(URL_CREATE_DOC, {
      method: 'POST',
      body: data,
      headers: {
        'Content-Type': 'multipart/form-data; boundary=stackoverflowrocks',
      }

然后用这个在我的 PHP Api 中接收

var_dump($request->files()->all());

但是没有数据!在标题中,我看到前面发送的数据很好,当我创建 var_dump($request->server()) 时,如果我发送文件,我会看到 CONTENT_LENGHT 发生变化。我觉得我做的不好,但是如何从多部分请求中获取数据?

【问题讨论】:

  • FormData 自动创建随机边界值本身。通过尝试在Content-Type 标头中指定boundary=stackoverflowrocks,您可能会破坏这里的东西- 标头说主体解析器应该寻找的边界是stackoverflowrocks,但实际上,它可能是一个完全不同的边界。不要自己设置 Content-Type 标头 - fetch 和 FormData 能够自己解决这个问题。 muffinman.io/blog/…
  • 非常感谢@Cbroe!这是我的问题,我刚刚删除了Content-Type 行,它起作用了!这两天你解决了:)

标签: javascript php reactjs multipartform-data


【解决方案1】:

根据readme

$request->
    id($hash = true)                    // Get a unique ID for the request
    paramsGet()                         // Return the GET parameter collection
    paramsPost()                        // Return the POST parameter collection
    paramsNamed()                       // Return the named parameter collection
    cookies()                           // Return the cookies collection
    server()                            // Return the server collection
    headers()                           // Return the headers collection
    files()                             // Return the files collection
    body()                              // Get the request body
    params()                            // Return all parameters
    params($mask = null)                // Return all parameters that match the mask array - extract() friendly
    param($key, $default = null)        // Get a request parameter (get, post, named)

files() 专门用于上传文件,您似乎没有;您的值可以在 POST 数据中找到,这意味着 paramsPost()params()param($name) 中的任何一个都是正确的。

【讨论】:

  • 感谢@Duroth 的回答。这是我的错,我在问题中放错了行,确实,$request->files()->all() 只是为了获取文件。我在尝试发送文件时使用了它。即使我使用paramsPost()params(),它也不起作用,它显示一个空数组。 @CBroe 为我带来了解决方案。
猜你喜欢
  • 1970-01-01
  • 2020-03-20
  • 2017-10-28
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多