View and Element UI combined for PDF previews prior to file uploading

I am currently utilizing Vue along with the element UI to enable file upload functionality, and I am also incorporating the pdfvuer node module. The uploaded files are ultimately being sent to Amazon S3.

My goal is to allow users to preview the file before clicking the confirm button. For reference, please see the image: upload

Currently, I have managed to implement a preview feature for PNG and JPG file types using the blob and createObjectUrl method, but this method does not work for PDF files. For reference, please see the image: upload and preview png

Below is the code snippet that includes the upload dialog:

HTML :

      <span class="pt-0">
        <p class="text-center mt-0">Please select the file you wish to import.</p>
        <el-upload
          accept="image/png, image/jpeg, application/pdf"
          class="avatar-uploader"
          :show-file-list="true"
          :before-upload="beforeAvatarUpload"
          action=""
        >
          <i class="fas fa-cloud-upload-alt fa-2x my-8" v-if="objectURL == ''"></i>


          <img :src="objectURL" width="100%" />
          <pdf :src="imageUrl.webkitRelativePath" />


          <div class="el-upload__text" v-if="objectURL == ''">Click here to execute</div>
          <div class="el-upload__tip" slot="tip">
            You can only upload PDF/PNG/JPG files.
          </div>
        </el-upload>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogUploadFile = false">Cancel</el-button>
        <el-button type="danger" @click="handleUploadFile">Confirm</el-button>
      </span>
    </el-dialog>

JS :

data(){ return ... }
methods:{
   beforeAvatarUpload(file) {
      this.objectURL = window.URL.createObjectURL(new Blob([file]));
      this.imageUrl = window.URL.createObjectURL(new Blob([file]));
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isPDF = file.type === "application/pdf";
      const isLt2M = file.size / 1024 / 1024 < 20;
      switch (file.type) {
        case "image/png":
          this.fileType = 1;
          break;
        case "image/jpeg":
          this.fileType = 2;
          break;
        case "application/pdf":
          this.fileType = 3;
          break;
        default:
          break;
      }
      return isJPG && isPNG && isPDF && isLt2M;
    },
}

I would greatly appreciate it if someone could assist me in resolving this issue or suggest an alternative approach to rewriting the code. If more detailed information about my code is required, please feel free to reach out.

Answer №1

Success! After searching for a while, I finally discovered the answer to my query. I utilized the <embed> tag to access the preview feature.

This is the code I used:

<input @change="handleChange" />

// preview area
<embed
    v-if="embedSrc"
    type="video/webm"
    :src="embedSrc"
    width="100%"
    style="max-height: 50rem; min-height: 20rem"
/>

...
data:{
  return {
    embedSrc: ''
  }
}
...
methods:{
   handleChange(){
      this.embedSrc = URL.createObjectURL(event.target.files[0]);
   }
}

Important note: remember to include : before src to ensure dynamic src functionality.

Answer №2

Have you attempted replacing the && with ||?

return isJPG || isPNG || isPDF || isLt2M;

Alternatively, how about this:

return (isJPG || isPNG || isPDF) && isLt2M;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update of a window occurs automatically

When a user clicks a link on a web page, I open a new window. $('#visit').click(function () { window.open(getHostName() + "/visits" , 'VisitsReport'); }); Within the web page $(document).ready(function () { var initializeVis ...

Guide to taking a screenshot of an HTML page using Javascript, Jquery, and HTML5 functionality

I am looking to add a unique feature to my website - the ability to capture the current image of my webpage with just the click of a button. Inspired by Google's "send feedback" function, I want to implement something similar on my own site. After res ...

Sending Paypal IPN Data to Node.JS: A Step-by-Step Guide

I'm looking to implement a real-time donation system on my website that can update all users simultaneously. The challenge I'm facing is that the IPN (Instant Payment Notification) page, responsible for verifying payments, is written in PHP. Unf ...

Displaying the value of HTML in JavaScript is not possible

When attempting to use JavaScript to alert the selected textarea value, I encountered a problem. My code $("#kandungan_email").html(); is unable to capture the &#13;&#10; characters within the HTML content. Here is the snippet of my code ...

Issue arising from background change upon component focus

My component needs to change its background color when focused, but for some reason it's not working. The hover effect works fine, but the focus doesn't. Can anyone assist me with this issue? import { CardContainer } from './styles' in ...

Adding a space after a comma automatically upon saving changes in VSCode

Whenever I input code (t,s) into the system and make changes to it, it automatically transforms into (t, s) with an added space after the comma. Is there a way to avoid VScode from adding this extra space on its own? ...

Increase the div id using jQuery

I've got this code snippet here and, oh boy, am I a newbie. How can I increase the number in the div using a jQuery script? if($res >= 1){ $i=1; while($row = mysqli_fetch_array($qry)){ echo "<div clas ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

A guide on implementing the IF statement to prevent the Weather API fetch from crashing when the user inputs an incorrect city name

Explaining The Issue - Objectives of the Task Creating a weather application that displays data from the OpenWeather API on the screen. - Current and Desired Outcomes Regardless of whether the user enters a valid city name or leaves the field blank, n ...

Outdated JavaScript Alert

Is it possible to use JavaScript to create an alert message in my input field when a past date is selected? I would like the warning to say "past date, please enter a valid date." <html lang="en"> <head> <meta charset="U ...

Loading forms on page load in CodeIgniterWould you like to

Is there a way to include onload javascript in CodeIgniter forms? I want to be able to do something like this within CodeIgniter: form onload="yourscript" Since CodeIgniter uses the form_open() command, I'm unsure how to incorporate the onload scrip ...

Choosing the next SELECT element with jQuery

JavaScript document.querySelectorAll('select[id^="_taskAssignedTo_"]').forEach(function(select) { if (select.value === "1") { select.nextElementSibling.querySelector('select[id^="_taskStatus_"]').disabled = false; } }); ...

"Troubleshooting Issue: Why Props in mapStateToProps Aren't Updating After Running an Action in Redux

Adding some context, I utilize Redux to manage updates in a shopping cart list. Essentially, I retrieve the list, add an item to it, and then update the entire list. However, after executing an action, my cartList does not seem to update. Despite consulti ...

Ways to access deeply nested data in Vuex store

I am facing an issue with my Vue project. I need to watch some Vuex store values and here is the code I have written: computed: { serverCategories: { get() { return this.$store.state[this.storeName].serverFilters.categories[0].value ...

Guide on resizing a ReactJS component for optimal browser display

Is there a way to resize a pre-existing React component within a browser that already has predetermined height and width? componentDidMount(x,y,z){ this.setState({height:window.innerHeight+'px'}); } I'm unsure if this approach is the corr ...

Potential Scope Problem in Angular JS Controller

The HTML code snippet I have is as follows: <body ng-controller = "Control as control"> <button ng-click = "control.prepareAction()">Do Action </button> <div id="one" ng-hide = "!control.showOne" > <div> <h6> ...

Strange Actions with JQuery Drag-and-Drop Functionality

Apologies for my limited experience with JQuery UI, but I am in the process of creating a web-based chess engine for 2 players using JavaScript. Instead of point and click, I have decided to implement a user-friendly drag and drop feature for non-mobile us ...

Verify if the item already exists in the Vue.js array

Here is the data I have: data: function() { return { conversations: [ ] } } I am retrieving my data from the response object using response.data.conversation Is there a method to verify if this.conve ...

Elements on the page appear and disappear as you scroll down

Whenever my scroll reaches the bottom of element B, I want my hidden sticky element to appear. And when I scroll back up to the top of element B, the sticky element should be hidden again. Here are my codes: https://i.sstatic.net/J49dT.jpg HTML <htm ...

Sequelize associations are not functioning optimally as expected

Trying to display a nested relationship: Cat.hasMany(legs) Leg.belongsTo(cat) Leg.hasOne(paw) paw.hasMany(leg) This is the Cat Model: module.exports = (sequelize, DataTypes) => { const Cat = sequelize.define('Cat', { us ...