首页 > 解决方案 > 如何从请求中获取上传的文件?

问题描述

为什么当我尝试从请求中获取上传的文件时总是NULL打开?dump()

我试图将 dropzone 链接到 Symfony 表单但我失败了(不可能在彼此内部做 2 个表单)

所以我做了一个新的控制器测试(我尽可能简单)

如何在控制器中使用 dropzone 检索上传的图像?

控制器代码:

<?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>

标签: javascriptphpsymfonyuploaddropzone.js

解决方案


我认为您正在尝试使用 fetch API 将其发送到服务器。

如果你想使用 Symfony 的 Request $request->file->get('file'),你需要将请求的主体包裹FormData()在 javascript 的对象中,如下所示:

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
   });

}

推荐阅读