javascript - 如何从请求中获取上传的文件?
问题描述
为什么当我尝试从请求中获取上传的文件时总是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>
解决方案
我认为您正在尝试使用 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
});
}
推荐阅读
- html - 垂直居中图像内的元素
- java - 将位置(来自 sql 的纬度和经度)标记到谷歌地图上时发生错误膨胀类片段
- r - 结构化主题模型(STM)如何确定最优主题数
- azure-devops - Specflow 生活文档生成器错误:多个文件与模式匹配
- javafx - 如何在打印前将节点(TableView)调整到 A4 纸上的可打印区域?
- async-await - 使用生成器函数等待先前的 api 响应以触发 redux saga 中的下一个 api 调用
- google-analytics - 渠道归因、硬编码分析与标签管理器的差异
- javascript - 比较然后根据数组键输出值
- reactjs - React.js 显示 Pusher 捕获的数据/事件
- javascript - 如何在打字稿中按值搜索这种树结构而不会超出最大堆栈调用