Я использую cakephp 2x. У меня проблема с полем загрузки изображения на странице редактирования. Каждый раз, когда я пытаюсь отредактировать страницу своего профиля, поле загрузки изображения отображается пустым. Информация в других полях остается такой же, как при заполнении формы добавления профиля, но поле изображения не позволяет получить сохраненное изображение. Я новичок в cakephp, если кто-нибудь знает, как мне получить изображение? плз помогите! И я также хочу знать, как я могу хранить более одного изображения, а также проверять, чтобы одно и то же изображение не загружалось дважды. Спасибо! Вот мой код загрузки изображения: >
// File upload function in Model.php
public $validate = array(
'image' => array(
'uploadError' => array(
'rule' => 'uploadError',
'message' => 'Something went wrong with the file upload',
'required' => FALSE,
'allowEmpty' => TRUE,
),
// http://book.cakephp.org/2.0/en/models/data- validation.html#Validation::mimeType
// custom callback to deal with the file upload
'imageOne' => array(
'rule' => 'imageOne',
'message' => 'Something went wrong processing your file',
'required' => FALSE,
'allowEmpty' => TRUE,
'last' => TRUE,
),
),
);
public function imageOne($check=array()) {
// deal with uploaded file
if (!empty($check['image']['tmp_name'])) {
// check file is uploaded
if (!is_uploaded_file($check['image']['tmp_name'])) {
return FALSE;
}
// build full filename
$filename = WWW_ROOT . $this->uploadDir . DS . Inflector::slug(pathinfo($check['image']['name'], PATHINFO_FILENAME)).'.'.pathinfo($check['image']['name'], PATHINFO_EXTENSION);
// @todo check for duplicate filename
/* if (!file_exists($check['image']['tmp_name'],$filename)) {
echo "Sorry, file already exists.";
}*/
// try moving file
if (!move_uploaded_file($check['image']['tmp_name'], $filename)) {
return FALSE;
// file successfully uploaded
} else {
// save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
$this->data[$this->alias]['filepath'] = str_replace(DS, "/", str_replace(WWW_ROOT, "", $filename) );
}
}
return TRUE;
}
public function beforeSave($options = array()) {
// a file has been uploaded so grab the filepath
if (!empty($this->data[$this->alias]['filepath'])) {
$this->data[$this->alias]['image'] = $this->data[$this->alias] ['filepath'];
}
// Controller.php
public function edit($id = null) {
if (!$this->CollegeProfile->exists($id)) {
throw new NotFoundException(__('Invalid college profile'));
}
if ($this->request->is(array('post', 'put'))) {
$this->request->data['CollegeProfile']['user_id'] = $this->Auth- >user('id');
$this->request->data['CollegeProfile']['id'] = $id;
if ($this->CollegeProfile->save($this->request->data)) {
$this->Session->setFlash(__('The college profile has been saved.'), 'default', array('class' => 'alert alert-success'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The college profile could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
}
} else {
$options = array('conditions' => array('CollegeProfile.' . $this->CollegeProfile->primaryKey => $id));
$this->request->data = $this->CollegeProfile->find('first', $options);
}
$this->loadModel('State');
$states = $this->State->find('list');
$this->set(compact('states'));
}
//Edit.ctp
Подробнее здесь: https://stackoverflow.com/questions/305 ... d-is-blank
При редактировании файла поле для загрузки пустое ⇐ Php
Кемеровские программисты php общаются здесь
-
Anonymous
1728523160
Anonymous
Я использую cakephp 2x. У меня проблема с полем загрузки изображения на странице редактирования. Каждый раз, когда я пытаюсь отредактировать страницу своего профиля, поле загрузки изображения отображается пустым. Информация в других полях остается такой же, как при заполнении формы добавления профиля, но поле изображения не позволяет получить сохраненное изображение. Я новичок в cakephp, если кто-нибудь знает, как мне получить изображение? плз помогите! И я также хочу знать, как я могу хранить более одного изображения, а также проверять, чтобы одно и то же изображение не загружалось дважды. Спасибо! Вот мой код загрузки изображения: >
// File upload function in Model.php
public $validate = array(
'image' => array(
'uploadError' => array(
'rule' => 'uploadError',
'message' => 'Something went wrong with the file upload',
'required' => FALSE,
'allowEmpty' => TRUE,
),
// http://book.cakephp.org/2.0/en/models/data- validation.html#Validation::mimeType
// custom callback to deal with the file upload
'imageOne' => array(
'rule' => 'imageOne',
'message' => 'Something went wrong processing your file',
'required' => FALSE,
'allowEmpty' => TRUE,
'last' => TRUE,
),
),
);
public function imageOne($check=array()) {
// deal with uploaded file
if (!empty($check['image']['tmp_name'])) {
// check file is uploaded
if (!is_uploaded_file($check['image']['tmp_name'])) {
return FALSE;
}
// build full filename
$filename = WWW_ROOT . $this->uploadDir . DS . Inflector::slug(pathinfo($check['image']['name'], PATHINFO_FILENAME)).'.'.pathinfo($check['image']['name'], PATHINFO_EXTENSION);
// @todo check for duplicate filename
/* if (!file_exists($check['image']['tmp_name'],$filename)) {
echo "Sorry, file already exists.";
}*/
// try moving file
if (!move_uploaded_file($check['image']['tmp_name'], $filename)) {
return FALSE;
// file successfully uploaded
} else {
// save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
$this->data[$this->alias]['filepath'] = str_replace(DS, "/", str_replace(WWW_ROOT, "", $filename) );
}
}
return TRUE;
}
public function beforeSave($options = array()) {
// a file has been uploaded so grab the filepath
if (!empty($this->data[$this->alias]['filepath'])) {
$this->data[$this->alias]['image'] = $this->data[$this->alias] ['filepath'];
}
// Controller.php
public function edit($id = null) {
if (!$this->CollegeProfile->exists($id)) {
throw new NotFoundException(__('Invalid college profile'));
}
if ($this->request->is(array('post', 'put'))) {
$this->request->data['CollegeProfile']['user_id'] = $this->Auth- >user('id');
$this->request->data['CollegeProfile']['id'] = $id;
if ($this->CollegeProfile->save($this->request->data)) {
$this->Session->setFlash(__('The college profile has been saved.'), 'default', array('class' => 'alert alert-success'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The college profile could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
}
} else {
$options = array('conditions' => array('CollegeProfile.' . $this->CollegeProfile->primaryKey => $id));
$this->request->data = $this->CollegeProfile->find('first', $options);
}
$this->loadModel('State');
$states = $this->State->find('list');
$this->set(compact('states'));
}
//Edit.ctp
Подробнее здесь: [url]https://stackoverflow.com/questions/30527022/on-editing-file-upload-field-is-blank[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия