【问题标题】:How to submit a multipart form with Goutte / Guzzle如何使用 Goutte / Guzzle 提交多部分表单
【发布时间】:2016-10-27 12:01:12
【问题描述】:

尝试测试一个可以上传图片并有一些隐藏字段的表单,如下所示:

<form class="add" action="https://example.com/stSPyOCwDVg" method="post" enctype="multipart/form-data">
    <input type="hidden" name="tokenCode" value="U2FsdGVkX18zMTY1MjMxNuUCJfrsNa-cT0yap3xGbgrDN6RkCLpTbOm8JLusrW1vGGQxqAdYYdE">
    <input type="file" name="file" multiple>
    <button class="addbtn" type="submit" name="go">add image</button>
</form>

期待提交类似于非多部分表单,但事实并非如此。而是尝试如下 POST:

// load the form page
$client = new Client();
$crawler = $client->request('GET', 'https://example.com/form');

// uploading params and files as per docs
$form = $crawler->selectButton('add image')->form(); // locate the upload form by button name
$post_url = $form->getUri();  // 'action' attrib on the form
$params = $form->getValues(); // grab hidden fields
$files = ['/tmp/UL_img1', '/tmp/UL_img2', '/tmp/UL_img3'];
$crawler = $client->request('POST', $post_url, $params, $files);

echo $crawler->html();

这只是返回原始表单,没有上传任何文件。有谁知道这是否被正确调用?

【问题讨论】:

    标签: php symfony multipartform-data guzzle goutte


    【解决方案1】:

    这可能不是理想的解决方案,但这确实有效:

    $form = $crawler->selectButton('add image')->form();
    $files = ['/tmp/UL_img1', '/tmp/UL_img2', '/tmp/UL_img3']
    foreach($files as $file) {
        $form['file'] = $tmpfname; // this was key
        $browser = $client->submit($form);
    }
    

    基本上,文件名可以分配给“文件”输入。这样我们就不必担心与请求一起发送的正确 POST url / hidden attribs / cookies。

    同一请求中的多个文件尚无法使用。会更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多