How to remove the uploaded file

Hello Yii forum, :)

I just could not figure out how to remove the attachment that a user accidentally clicked Browse button of type fileField in the add/edit form, though he doesn’t want to upload a file.

Anyone know how to do this?


do you mean remove from form field prior to user click on submit button or remove unnecessary file from server ?

Yeah… I think the 1st one you said is what I meant to do. Surely, it is not about the server or save the form yet. I just thought that probably it is about removing the temporary memory in cache or something in client’s computers.

The better description is like the way we write an email with attachment included.

What if we change our mind and want to remove the attachment file later?

Writing an email we would have a cancel link to remove the file attached or AJAX link. Is there anything like that provided by Yii at all? :huh:

Uploaded files are stored in a temporary location by PHP itself. They will be dealt with once the request has been processed. Unless, of course, you’ve copied an uploaded file via CUploadedFile.saveAs(). In this case, you would have to purge the unwanted file yourself via unlink().

There is two ways to clear file input:

  • using Reset form button. But this button will clear entry form - so this is not suitable in your case.
  • do this using JavaScript - this way we will do.

Example solution:

<form name="file-form" action="index.php">

  <input type="file" name="file-input" id="file-input"/>

  <button onclick="$('#file-input').val('');return false;">Clear file input</button>


Sure better include JS event handlers via jQuery bind/delegate methods. But this example only demonstrates how to clear file-input.

Now it works!!!

Thank you so much MadAnd

And Danke schön Da:Sourcerer


Is there a way to clear the file input in AR model?

<div class="row">

<?php echo CHtml::form(’’,‘post’,array(‘enctype’=>‘multipart/form-data’)); ?>

<?php echo CHtml::activeFileField($model, ‘file’,array(‘multiple’ => true)); ?>


Thanks in advance.

This can be achieved in the same way, but first we need to explicitly define the file field ID to be able to clear it. Result should look like this:

<div class="row">

	<?php echo CHtml::beginForm('','post',array('enctype'=>'multipart/form-data')); ?>

	<?php echo CHtml::activeFileField($model, 'file', array('multiple' => true, 'id'=>'file-input')); ?>

	<button onclick="$('#file-input').val('');return false;">Clear file input</button>

	<?php echo CHtml::endForm(); ?>