该问题曾被问过,但我已经从另一个问题中解决了问题,但我仍然无法使它起作用。单击按钮提交表单数据后,出现错误:调用字符串的成员函数guessExtension()(500 Internal Server Error)。这取自“网络”选项卡中的响应。我确信没有字符串,因为我已经检查过了,它以键值对的形式给我提供了数组形式的数据(用重定向并转储$ file变量的普通请求检查了它)。 这是我的控制器的代码:
/**
* @Route("/upload", name="uploadpic")
* @param Request $request
* @return JsonResponse|\Symfony\Component\HttpFoundation\Response
*/
public function uploadAction(Request $request){
if(!$request->isXmlHttpRequest()){
return new JsonResponse(
array(
'message' => 'Error',
'status' => 'Not received'
), 400);
}
$user = $this->get('security.token_storage')->getToken()->getUser();
$formed = $this->createForm(UserPicType::class, $user);//dadoh v barzinata User::class i gramna s: class does not implement “Symfony\Component\Form\FormTypeInterface”
$formed->handleRequest($request);
if(isset($request->request)) {
$file = $request->files->get('user_pic_type')['userPic'];
$file = $user->getUserPic();
$fileName = $this->generateUniqueFileName() . '.' . $file->guessExtension();
$file->move(
$this->getParameter('users_directory'),
$fileName
);
$user->setUserPic($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('profile');
}
return $this->render('default/index.html.twig',
['formed' => $formed->createView(),
'posts' => null]);
}
private function generateUniqueFileName()
{
return md5(uniqid());
}
这是我的ajax请求:
$("#submit_pic").on('click', function(event){
event.preventDefault();
event.stopPropagation();
$.ajax({
type: "post",
url: "/upload",
data: new FormData($("#pic_data")[0]),
processData: false,
contentType: false,
success: function () {
console.log('success');
},
error: function (response) {
console.log(response);
}
});
});
我的模板:
<form method="POST" enctype="multipart/form-data" action="{{ path('uploadpic') }}">
<p>
<input type="file" id="pic_data" name="user_pic_type[userPic]" required>
</p>
<button type="submit" id="submit_pic" name="" class="btn btn-success btn-sm">
Change
</button>
</form>
当我使用dump($file)
时:
DefaultController.php on line 62:
UploadedFile {#38 ▼
-test: false
-originalName: "filedd.jpg"
-mimeType: "image/jpeg"
-size: 7256
-error: 0
path: "C:\xampp\tmp"
filename: "phpB394.tmp"
basename: "phpB394.tmp"
pathname: "C:\xampp\tmp\phpB394.tmp"
extension: "tmp"
realPath: "C:\xampp\tmp\phpB394.tmp"
aTime: 2019-01-02 02:08:13
mTime: 2019-01-02 02:08:13
cTime: 2019-01-02 02:08:13
inode: 0
size: 7256
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\xampp\tmp\phpB394.tmp"
}
因此,当我使用刷新/重定向我的普通请求时,确实在数据库和文件夹中获取文件,但是当我尝试使用ajax时,它会吐出错误。知道为什么吗?