我过去用 AJAX JQUERY
完成了文件上传,但现在我正在尝试用symfony FileType
做同样的事情 .
问题是在正常工作流程中我们需要添加 contentType: false, processData: false,
但这似乎导致以下symfony错误: Cannot check if an unsubmitted form is valid. Call Form::isSubmitted() before Form::isValid().
所以 isSubmitted()
总是假的,我猜是因为 processData: false
我完全失去了如何解决这个问题,因为如果我不做 contentType: false
,那么AJAX请求会崩溃 . symfony文档对此不满意 .
JAVASCRIPT:
const form_data = $('#newBrandForm').serializeArray();
const json = serializeAsObject(form_data)
const files = document.getElementById('new_brand_group_logo_logoFile').files;
if (files.length > 0) {
let formData = new FormData();
for (let x = 0; x < files.length; x++) {
formData.append("attachements", files[x]);
}
json['new_brand[group_logo][logoFile]'] = formData
}
$.ajax({
url: `/new-brand-form-handle`,
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: json
})
CONTROLLER
function brandFormHandle(Request $request) {
$em = $this->getDoctrine()->getManager();
$brandEntity = new Brand();
// create form
$form = $this->createForm(NewBrandType::class, $brandEntity);
// handle
$form->handleRequest($request); // CRASH HERE
if ($form->isSubmitted() && $form->isValid()) {
$brand = $form->getData();
// move file
$someNewFilename = 'newBrand'.'-logo';
$file = $form['attachment']->getData();
$file->move($this->directory, $someNewFilename);
try {
$em->persist($brand);
$em->flush();
$status = 'Brand added';
} catch (Exception $ex) {
return $this->json([2, 'insertion error'.$ex]);
}
return $this->json([1, $status]);
}
//....
}
$request
DUMP所以我可以看到那里的文件,但看起来表单只是一个对象,所以我不确定这是不是问题?
Request {#51 ▼
+attributes: ParameterBag {#71 ▶}
+request: ParameterBag {#87 ▼
#parameters: array:1 [▼
"form" => "[object Object]"
]
}
+query: ParameterBag {#70 ▶}
+server: ServerBag {#35 ▶}
+files: FileBag {#73 ▶}
+cookies: ParameterBag {#72 ▶}
+headers: HeaderBag {#82 ▶}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/new-brand-form-handle"
#requestUri: "/new-brand-form-handle"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: Closure {#111 ▶}
#locale: null
#defaultLocale: "en"
-isHostValid: true
-isForwardedValid: true
basePath: ""
format: "html"
}
//这是来自console.log(json)的转储,注意没有文件;我不确定这是否正常
Object
new_brand[group_description][description]: "description"
new_brand[group_identification][city]: ""
new_brand[group_identification][country]: "AU"
new_brand[group_identification][name]: "name"
new_brand[group_identification][postcode]: ""
new_brand[group_identification][streetAdd]: ""
new_brand[group_identification][street]: "street"
new_brand[group_identification][website]: "website"
new_brand[group_logo][logoURL]: "web"