I'm trying to implement an image preview. It works fine until i came to a problem where i need to prevent the input file
to not change.
When trying to change to image its fine. After changing to image try to change the input file into a txt
file. its alerting the correct error, but the input file is also changed.
$('body').on('change','.input-preview',function(e){
var ito = $(this);
var img = ito[0].files;
var errs = [];
for(x=0;x<img.length;x++){
if(img[x].type!=='image/jpeg' && img[x].type!=='image/gif' && img[x].type!=='image/png'){
errs.push('Not image.');
break;
}
if(img[x].size>(1024000 * 5)){
errs.push('File is too big.');
break;
}
}
if(errs.length){
e.preventDefault();
alert(errs[0]);
return false;
}else{
previewIt(this, $('.preview-profile'));
}
});
The change
event is not cancelable. See the document on MDN .
Since change
is not a cancelable
event, you can manually remove an item when you want to "cancel" it.
The following example will not accept files of size > 1024 bytes.
$("#fileInput").change(function() { if (this.files[0].size > 1024) { $("#result").text("File size exceeds 1024 bytes"); this.value = ""; } else { $("#result").text("OK"); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" id="fileInput"/> <div id="result"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.