MongoGridFS::storeUpload
(PECL mongo >=0.9.0)
MongoGridFS::storeUpload — Stores an uploaded file in the database
Описание
Список параметров
-
name
-
The name of the uploaded file to store. This should correspond to the file field's name attribute in the HTML form.
-
metadata
-
Other metadata fields to include in the file document.
Замечание:
Данные поля могут перезаписать поля, автоматически созданные драйвером, как указано в основной документации MongoDB » коллекции файлов. В качестве практического применения данного поведения можно указать собственный chunkSize или _id для файла.
Замечание:
The filename index will be populated with the filename used.
Возвращаемые значения
Возвращает _id сохраненного документа. Это будет сгенерированный MongoId, за исключением случая, когда _id был явно указан в параметре extra
.
Список изменений
Версия | Описание |
---|---|
1.2.5 | Changed second parameter to an array of metadata. Pre-1.2.5, the second parameter was an optional string overriding the filename. |
Примеры
Пример #1 MongoGridFS::storeUpload() HTML form example
Suppose you have the following HTML form:
<form method="POST" enctype="multipart/form-data"> <label for="username">Username:</label> <input type="text" name="username" id="username" /> <label for="pic">Please upload a profile picture:</label> <input type="file" name="pic" id="pic" /> <input type="submit" /> </form>
If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:
<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();
$gridfs->storeUpload('pic', array('username' => $_POST['username']));
?>
Смотрите также
- MongoGridFS::put() - Stores a file in the database
- MongoGridFS::storeBytes() - Stores a string of bytes in the database
- MongoGridFS::storeFile() - Stores a file in the database
- MongoDB core docs on » GridFS
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MongoDB
- Классы GridFS
- Функция MongoGridFS::__construct() - Creates new file collections
- Функция MongoGridFS::delete() - Delete a file from the database
- Функция MongoGridFS::drop() - Drops the files and chunks collections
- Функция MongoGridFS::find() - Queries for files
- Функция MongoGridFS::findOne() - Returns a single file matching the criteria
- Функция MongoGridFS::get() - Retrieve a file from the database
- Функция MongoGridFS::put() - Stores a file in the database
- Функция MongoGridFS::remove() - Removes files from the collections
- Функция MongoGridFS::storeBytes() - Stores a string of bytes in the database
- Функция MongoGridFS::storeFile() - Stores a file in the database
- Функция MongoGridFS::storeUpload() - Stores an uploaded file in the database
Коментарии
I am not able to upload an image using this code.
Getting this error
Fatal error: Uncaught Error: Call to undefined method MongoDB\Database::getGridFS() in C:\xampp\htdocs\phpmongodb\new.php:4 Stack trace: #0 {main} thrown in C:\xampp\htdocs\phpmongodb\new.php on line 4
For my PHP 7.0.27 this is incompatible to the "multiple" tag on inputs.
Like this:
<input type="file" name="files[]" multiple>
Please note that you need to use 'files[]', as else only one file is used from the uploaded files.
As documented, you need to give the Index into $_FILES as the first argument to this function. Like in:
foreach ($_FILES as $k=>$v)
$db->getGridFS()->storeUpload($k, $v);
However in the case of "multiple" selects, the corresponding entry in $_FILES[$k]["name"] is an array of filenames, not just a single filename. This is true even for a single file, in that case it is an array with just a single string in it.
In that case the function just silently fails. No error, no problem shown, it just becomes a NOP.
The workaround is:
- Without JavaScript, fallback to single file upload.
- With JavaScript add "multiple", and do the upload with Ajax file-by-file.
- As then only single files reach PHP, the problem is solved.
For multiple uploads storeUploads should be implemented.
But as we have possibility to use direct storeFile then it makes no sense because custom form was used anyway.