P
P
prozrost2017-03-13 13:19:58
JavaScript
prozrost, 2017-03-13 13:19:58

How to remove an image using ajax request?

There is a field for uploading files in the view (multiple upload)

<?= $form->field($images, 'imagesFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>

There is also a method in the controller that processes everything, receiving images through
$images->imagesFiles = UploadedFile::getInstances($images, 'imagesFiles');

Now I want to have a kind of preview of these not yet loaded pictures in the view, but the most important thing is that they can be deleted. Maybe someone did something like that.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-03-13
@webinar

so that they can be removed
their whom? Files or previews, since js usually creates previews before uploading to the server. For
yii2 there are widgets with previews, from adequate ones:
https://github.com/2amigos/yii2-file-upload-widget
demos.krajee.com/widget-details/fileinput
if there is an attribute for the model, let's say "image_name" which stores the name of the photo, then the action looks something like this:
public function actionDeleteMyImage($id){
  if($model = MyModel::findOne($id)){
    $path = '/путь/к/папке/с/картинками/от/корня/сервера/'.$model->image_name;
    if(file_exists($path)){
      unlink($path);
      return true;
    }
  }
  return false;
}

K
k0nsu1, 2017-03-13
@k0nsu1

For previews of images that have not yet been uploaded, you will need a FileReader in javascript, or first send the file to the server, process it there and give a link to the preview.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question