簡體   English   中英

如何從請求中獲取上傳的文件?

[英]How can I get the uploaded files from the request?

當我嘗試從請求中獲取上傳的文件時,為什么我總是在dump()上得到NULL

我試圖將 dropzone 鏈接到 Symfony 表單,但我失敗了(不可能在彼此內部執行 2 forms)

所以我做了一個新的 controller 測試(我盡可能簡單)

如何在 controller 中使用 dropzone 檢索上傳的圖像?

Controller 代碼:

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class TestController extends AbstractController
{
    /**
     * @Route("/test", name="test")
     */
    public function index(Request $request)
    {
        dump($request->files->get('file'));

        return $this->render('test/index.html.twig');
    }
}

HTML 代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" integrity="sha256-e47xOkXs1JXFbjjpoRr1/LhVcqSzRmGmPqsrUQeVs+g=" crossorigin="anonymous" />
    <div class="row">
        <div class="col-sm-4">
            <form action="{{ path('test')}}" method="POST" enctype="multipart/form-data" class="dropzone">
            <div class="fallback">
                  <input type="file" name="file" />
            </div>
            </form>

        </div>
    </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js" integrity="sha256-cs4thShDfjkqFGk5s2Lxj35sgSRr4MRcyccmi0WKqCM=" crossorigin="anonymous"></script>

</body>
</html>

我認為您正在嘗試使用提取 API 將其發送到服務器。

如果你想使用 Symfony 的請求$request->file->get('file') ,你需要將請求的主體包裝在 javascript 中的FormData() object 中,如下所示:

function send() {

   const form = document.querySelector(`form`),
     body = new FormData(form);

   fetch(form.action, { // if you need the response, you can assign fetch to a variable
    method: `POST`,
    body
   });

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM