Rob
Rob

Reputation: 6380

Detect file type from front end upload and display differently depending on jpg/png or pdf?

I've created a front end system that allows people to submit images and pdf's.

In hindsight we would've separated this out into two separate fields but it's too late for that now, as there's over 500 submissions.

How can I first detect what format the file is then either display it as an img if it's jpg/png or display it as a link if it's a pdf?

Here's the code at the moment:

<?php if(get_field('submit_image_or_pdf1') != "") { ?>
<img src="<?php echo the_field('submit_image_or_pdf1');?>" alt="<?php echo the_title(); ?> - <?php echo the_field('submit_submission_production_title'); ?>" /> 
<?php } ?>

This is what actually outputs the file no matter the format:

<?php echo the_field('submit_image_or_pdf1');?>

Update:

<?php $field = get_field('submit_image_or_pdf1');
    function ($field) {
    if ($_FILES[$field]['type'] == 'application/pdf') { ?>
        <a href="<?php echo the_field('submit_image_or_pdf1');?>">View PDF</a>
        <br /><br /><br /><br />
    <?php } else { ?>
        <img src="<?php echo the_field('submit_image_or_pdf1');?>" alt="<?php echo the_title(); ?> - <?php echo the_field('submit_submission_production_title'); ?>" /> 
        <br /><br /><br /><br />
    <?php } ?>
<?php } ?>

Upvotes: 0

Views: 181

Answers (1)

chrislondon
chrislondon

Reputation: 12041

You can always get the extension out of the posted file field. It's not completely accurate since you could name any file '.pdf'. So be careful when accepting files form users as they could contain viruses or something else.

function the_field($fileFieldName) {
    if ($_FILES[$fileFieldName]['type'] == 'application/pdf') {
        echo '<a href="/download-the-file-link">Download</a>';
    } else {
        echo '<img src="/the-image-source" />';
    }
}

UPDATE: The following example works where get_field() returns the path of the file.

<?php $field = pathinfo(get_field('submit_image_or_pdf1'));?>
<?php if (isset($field['extension']) && $field['extenstion'] == 'pdf') { ?>
    <a href="<?php echo the_field('submit_image_or_pdf1'); ?>">View PDF</a>
<?php } else { ?>
    <img src="<?php echo the_field('submit_image_or_pdf1'); ?>" alt="<?php echo the_title(); ?> - <?php echo the_field('submit_submission_production_title'); ?>" /> 
<?php } ?>

<br /><br /><br /><br />

Upvotes: 1

Related Questions