Jump to content
  • 0

Requiring File Type = Image AND Providing an Image Preview


DaveS

Question

Hello, Community,I'm trying to use these two community posts together:  

  1. Restricting File Types that Can Be Uploaded
  2. Previewing an Image before it is Uploaded

They don't seem to get along - if I keep the preview, then my validation generates an alert, but it doesn't prevent the user from uploading the file.  

My footer code currently looks like this:

<script>
/*   PREVIEW CODE CURRENTLY COMMENTED OUT BECAUSE RESTRICTING FILE TYPE IS MORE IMPORTANT THAN PREVIEW ********************
document.getElementById("InsertRecordLogo").setAttribute("onchange","loadFile(event)");
    var loadFile = function(event) {
    var output = document.getElementById('output');
    output.src = URL.createObjectURL(event.target.files[0]);
  };
*************************** */
</script>
<script type="text/javascript">
var file = document.getElementById('InsertRecordLogo');
var extensions = ['jpg','jpeg','png','svg'];
file.addEventListener('change', function(e) {
var ext = this.value.match(/.([^.]+)$/)[1];
console.log(ext);
if (!extensions.includes(ext)){
alert('Invalid file format. Please upload only image files of type jpg, jpeg, png or svg');
this.value = '';
}
});
</script>

 

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Hi @DaveS,

I suggest posting these under the JavaScript forum section. I tried to merge both solutions though I modified the behavior a little bit. My file field name is "File_Field".

HTML Block:

<img id="output" height="300px" style="display:none;" onerror="this.style.display='none'"/>

Footer with code:

<script type="text/javascript">
var file = document.getElementById('InsertRecordFile_Field');
var extensions = ['jpg','jpeg','png','svg'];
file.addEventListener('change', function(e) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(e.target.files[0]);
output.style.display = 'block';
var ext = this.value.match(/.([^.]+)$/)[1];
console.log(ext);
if (!extensions.includes(ext)){
alert('Invalid file format. Please upload only image files of type jpg, jpeg, png or svg');
this.value = '';
}
});
</script>

With this one, the file preview will only load if there is a correct format selected. By default or on error, it is hidden.

Hope this helps :)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...