[英]How to upload a image using Slim Framework
I want to storage a image in server and save the path in MySQL, but i'm not finding a good code to do it.我想在服务器中存储图像并将路径保存在 MySQL 中,但我没有找到一个好的代码来做到这一点。
I found this, but does not work:我找到了这个,但不起作用:
$container = $app->getContainer();
$container['upload_directory'] = __DIR__ . '../uploads';
$app->post('/photo', function (Request $request, Response $response) use ($app) {
$directory = $this->get('upload_directory');
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['picture'];
if($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$response->write('uploaded ' . $filename . '<br/>');
}
});
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename(),
PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
Somebody knows how to upload image and save the path in MySQL?有人知道如何上传图像并将路径保存在 MySQL 中吗?
First you need a database connection for MySQL.首先,您需要 MySQL 的数据库连接。 Read more
阅读更多
Then create a table, eg files(id, path, filename)然后创建一个表,例如 files(id, path, filename)
To insert the record (after the upload) into the table, you could use an SQL statement as follows:要将记录(上传后)插入表中,可以使用 SQL 语句,如下所示:
// ...
$filename = moveUploadedFile($directory, $uploadedFile);
$response->getBody()->write('File uploaded: ' . $filename);
$row = [
'path' => $directory,
'filename' => $filename
];
$sql = "INSERT INTO files SET path=:path, filename=:filename;";
$pdo->prepare($sql)->execute($row);
// ...
return $response;
Please note that $response->write('...')
will not work.请注意
$response->write('...')
将不起作用。 It must be $response->getBody()->write('my content');
必须是
$response->getBody()->write('my content');
. .
Edit: Make sure that the uploads/
directory exists and the directory has write access.编辑:确保
uploads/
目录存在并且该目录具有写入权限。 For example chmod -R 1777 uploads/
例如
chmod -R 1777 uploads/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.