Displaying a binary PDF file in a web browser using JavaScript

I am facing an issue with displaying files from a MSSQL Server Database that are stored as a column Content of type VARBINARY(MAX) in a SQL table.

To access the database, I have developed a backend Node.js server using Express.js. There is a route called /api/file/:id_file which retrieves the content of the file with the specified id_file

async getFile(req,res){
    const {id_file} = req.query
    const file= await db.Files.findOne({
        where:{
            'Id': id_file,
        }
        
    })
    res.contentType('application/pdf')
    res.send(file.Content)
}

On the frontend side, I have implemented an iframe using Javascript

<iframe id="view" src="" style='height: 500px; width: 1000px;' />

I make an ajax request to retrieve the file and then convert it to base64 before setting it as the src attribute of the iframe element

const reader = new FileReader();
reader.onload = () => {
  const b64 = reader.result.replace(/^data:.+;base64,/, "");
  $('#view').attr('src','data:application/pdf;base64,'+ b64);
};
reader.readAsDataURL(new Blob([resp.data], { type: "application/pdf" }));

However, when attempting to display the file, the PDF appears blank and nothing is shown. Is there a step I may be missing in converting the file content to base64?

Answer №1

No filereader is needed in this case because the file has already been retrieved from the API, so there's no need to read it from the filesystem or user input. If your binary pdf data is stored in resp.data, you can simply utilize btoa

This function creates a Base64-encoded ASCII string from a binary string.

$('#view').attr('src','data:application/pdf;base64,'+ btoa(resp.data));

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

Steps to ensure a dropdown menu remains expanded when its nested menu is selected

Check out this dropdown list here, but the issue arises when clicking on a nested menu item such as "Books Registration". Once that page loads, the dropdown menu collapses like shown here. Here's a snippet of the dropdown code: <ul class="nav nav- ...

Managed to successfully deploy on Heroku, however encountered an Application Error when using Express + Node.JS

Embarking on my first deployment journey, I decided to try out Heroku. Please bear with me as I explore deploying for the first time as a fun practice project. Following the steps outlined in this helpful guide on deploying Heroku, I managed to successful ...

What is the best way to bring in styles to a Next.js page?

I am facing an issue with my app where I have a folder called styles containing a file called Home.module.css. Every time I try to include the code in my pages/index.js, I encounter the same error message saying "404 page not found.." import styles from & ...

Can I access the mongoose schema definition through swagger-jsdoc?

Recently, I completed a project using express.js with a MongoDB backend powered by mongoose. As I built the mongoose models through schemas, it crossed my mind whether there is a way to reference the schema definition instead of having to manually type out ...

Angular - Enhance ngFor index while filtering

I am currently working with a list that utilizes an *ngFor loop in the template: <li *ngFor="let product of products | filterProducts: selectedFilter; index as productId"> <a [routerLink]="['/product', productId]"> {{produc ...

Node/Angular/Express App encountering connection rejection on OPTIONS header due to nginx acting as a reverse proxy

I'm having trouble getting my express app to run on a Digital Ocean Ubuntu 12.04 droplet using nginx as a reverse proxy. Every time I attempt to POST a form, I encounter an OPTIONS net::ERR_CONNECTION_REFUSED error. Despite trying various nginx config ...

Rendering faces with a different texture using BufferGeometry in Three.js

Here is my output date: geom[0] = { texturesindexT: new Int16Array([0,1,2,3]), texturesindexS: new Int16Array([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,...]), materialsindexT: new Int16Array([-1,-1,-1,-1]), materialsindexS: new Int16Array([-1,0,1,2,3,4,5,0,6,2,7,8 ...

Arrange the divs in numerical order based on the number of downloads

I wrote a basic code to organize parent divs based on their titles. However, when I attempted to do the same for download counts, nothing happened - no errors or actions from the code. There are two functions in total, both of which are triggered by butto ...

Unable to pass React API test using Nock due to the error message "Nock: Request does not match any routes."

Check out the working Express Route code below, which functions perfectly in both back and frontend. // Edit/update by vessel_type by_id - Working router.put("/:id", (req, res, next) => { Vessel_Type.findByIdAndUpdate( req.params.id, req.bod ...

How to implement a "callWhenReady" function in JavaScript

I am new to javascript and currently working on restructuring my prototype code. The current setup involves multiple levels of nested callbacks, making it difficult to read and manage. I am aiming for a cleaner approach similar to the following: GoogleMap ...

Encountering an issue while attempting to integrate mongoose with vue and receiving an error

Whenever I attempt to import this code, the page throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'split') import { User } from '@/assets/schemas' export default { name: 'HomeView', mount ...

What steps should I take to fix the TypeScript Compiler issue "Global member 'NodeJS' has no exported namespace 'Global'?"

QUERY: What steps should I take to fix the Typescript Compiler (tsc) error stating "Namespace 'NodeJS' has no exported member 'Global'"? Upon executing tsc, this particular error unexpectedly appeared in a project that is considered "l ...

Tips for retrieving all results without any parameters specified in the request URL

When I make the request to http://localhost:3000/getAll?warranty=1&model=M4, it displays all details with warranty=1 and model=M4. However, if I request http://localhost:3000/getAll?warranty=1, it shows no results. Below is my request router: router ...

The function contacts.map is not defined

Can someone help me understand why I am getting the error message "contacts.map is not a function"? I am working on fetching data from a contacts array list that I have created. My goal is to display buttons inside a panel. When a button is clicked, the sc ...

React Router consistently displaying IndexRoute

This is the main file for my app: import React from 'react'; import { render } from 'react-dom'; import { browserHistory, Router, Route, IndexRoute } from 'react-router'; // Components import Main from './components/cor ...

What could be causing my React app to consistently reload whenever I save a file in my project?

Hi there, I am currently working on a project using React, GraphQL, Node, and MongoDB. I have been trying to upload images to a folder within my app, but I am facing an issue with the app reloading after saving the file. I attempted to manage a local state ...

Timed up 10-second countdown with vue.js

<html> <head> <meta charset="utf-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" ></script> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> < ...

Instructions for rotating a sphere simultaneously along the x, y, and z axes

Seeking assistance on how to properly rotate an image along all three axes using the Three Js library. Currently, rotation along one axis works fine, but when attempting rotation along all three axes, the results are abnormal. I have read about using quate ...

Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below: export class DtoTransactionCategory { categoryName: String; totalPrice: number; } Using groupBy function: import { groupBy} from 'lodash&apo ...

The property was computed but cannot be set - specifically for a toggle component

I am currently working on developing a switch toggle component in Vue that includes a v-model and @updated. However, I am encountering difficulties when trying to update the model once the user toggles the switch. Initially, I faced an issue regarding muta ...