[英]Empty $request->request and $request->files with multipart/form-data
I am trying to upload a form with a file to my server using AJAX, but Symfony doesn't parse the request body like it should.我正在尝试使用 AJAX 将带有文件的表单上传到我的服务器,但 Symfony 没有像它应该的那样解析请求正文。 This is my PHP:这是我的 PHP:
#[Route('/api/upload/file', name: "api_upload_file", methods: ['POST'])]
public function create(Request $request): JsonResponse
{
dump($request->files->all());
dump($request->request->all());
dump($request->getContent());
...
and the dump output (The file part is cut out because it takes a lot of space):和转储 output(文件部分被删除,因为它占用了大量空间):
[]
[]
"""
------WebKitFormBoundaryh4t0I09h9iTRNGme
Content-Disposition: form-data; name="subcategory"
1
------WebKitFormBoundaryh4t0I09h9iTRNGme
Content-Disposition: form-data; name="main_image"; filename=""
Content-Type: application/octet-stream
------WebKitFormBoundaryh4t0I09h9iTRNGme
Content-Disposition: form-data; name="more_images"; filename=""
Content-Type: application/octet-stream
------WebKitFormBoundaryh4t0I09h9iTRNGme
Content-Disposition: form-data; name="original_version"
------WebKitFormBoundaryh4t0I09h9iTRNGme
Content-Disposition: form-data; name="version"
------WebKitFormBoundaryh4t0I09h9iTRNGme
Content-Disposition: form-data; name="original_title"
------WebKitFormBoundaryh4t0I09h9iTRNGme
Content-Disposition: form-data; name="title"
"""
The request clearly gets through so I do not understand why the content is not parsed请求明明打通了,不明白为什么内容不解析
Just in case, here is the javascript part: (This looks like JQuery but is not)为了以防万一,这是 javascript 部分:(这看起来像 JQuery 但不是)
form.submit(e => {
e.preventDefault();
let formData = createItemForm.formData();
$.ajax('/api/upload/file', {
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(data => data.json())
.then(json => {
console.log('uploaded');
});
});
How should I do to get the files and the form values in $request->files and $request->request?如何获取$request->files和$request->request中的文件和表单值?
DO NOT specify the Content-Type
header yourself, when trying to make such a multipart request.尝试发出这样的多部分请求时,请勿自行指定Content-Type
header。 That header needs to include the boundary value (so that the receiver will know how to parse this request) - if you specify it yourself, as just multipart/form-data
, then that will be missing. header 需要包含边界值(以便接收方知道如何解析此请求)——如果您自己指定它,就像multipart/form-data
一样,那么它将丢失。
These request libraries usually know how to properly set it on their own, based on that you are passing in a FormData instance.这些请求库通常知道如何根据您传入的 FormData 实例自行正确设置它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.