我正在使用UploadedFile
symfony2 中的类来上传图像文件。我允许使用 mime 类型image/jpg
和image/png
. 当我从我的系统上传一个 png 文件到服务器时,它的 mime 类型会自动更改。我知道它发生了变化,因为当我触发这个命令时:
file --mime-type /home/mysuer/img.png
它给了我这个:
home/myuser/img.png: image/png
但是当我上传文件和打印UploadedFile
对象时,它会给出以下输出:
Array
(
[media] => Symfony\Component\HttpFoundation\File\UploadedFile Object
(
[test:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
[originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => img.png
[mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => application/octet-stream
[size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 1246
[error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
[pathName:SplFileInfo:private] => /tmp/phpivgnne
[fileName:SplFileInfo:private] => phpivgnne
)
)
任何人都可以提出什么问题吗?
编辑
这是我的代码:
public function postFileAction(Request $request)
{
print_r($request->files->all());//Prints All files
$image = $request->files->get('media');
echo $image->getClientMimeType();exit; //Mime Type Information
if (empty($image)) {
throw new FileException('Invalid File, Please Select a Valid File.');
}
$uploader = $this->get('application.file_uploader');
if (!$this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
//authenticated (NON anonymous users)
throw new InvalidParameterException('Invalid User, Please use valid credentials');
}
return $uploader->upload($image, $this->get('security.context')->getToken()->getUser()->getId());
}
PHPUnit 测试代码
public function testPostFile()
{
$file = tempnam(sys_get_temp_dir(), 'upl'); // create file
imagepng(imagecreatetruecolor(10, 10), $file); // create and write image/png to it
$image = new UploadedFile($file, 'new_image.png', 'image/png', 10, UPLOAD_ERR_OK);
$crawler = $this->client->request(
'POST', '/api/v1/files.json', array('submit' => 'Submit Form'), array('media' => $image)
);
$response = $this->client->getResponse();
$this->assertJsonResponse($response);
$this->assertContains('filename', $response->getContent());
print_r($response->getContent());exit;
$fileToken = json_decode($response->getContent());
$this->assertNotEmpty($fileToken->filename);
unlink($file);
unset($file, $image, $crawler, $response);
return $fileToken->filename;
}
我正在使用curl
命令提示符来测试我的 REST Web 服务文件上传,如下所示:
curl -X POST myapi.com/app_dev.php/api/v1/files.json --form "media=@/home/myuser/img.png"