PDF downloads but both pages are blank (resume download react.js) - javascript

My PDF download shows both pages, but they are completely blank.
The download seems to work but I cannot get it to properly show the contents of the PDF.
Here is the main code snippet I've tried, with the ResumeName.pdf file located in the public folder.
React component:
class Contact extends React.Component {
render() {
const pdfHandler = () => {
fetch('ResumeName.pdf').then(response => {
response.blob().then(blob => {
// Creating new object of PDF file
const fileURL = window.URL.createObjectURL(blob);
// Setting various property values
let alink = document.createElement('a');
alink.href = fileURL;
alink.download = 'ResumeName.pdf';
alink.click();
})
})
}
return (
<p>Please click <a onClick={pdfHandler}>here</a> to download my resume.</p>
);
}
};
The download worked using this method but it still showed as blank. I also tried having the pdfHandler as a separate script.js file and importing it but that did not work either. Another thing I tried was having the resume stored in the src directory, and the but the same issued still occurred with the blank pages.

Related

How to use the fetchImage function from the face-api.js

I am currently playing around with a face recognition in JavaScript.
I am new in JavaScript and faced some problems and I hope you can help me out with this. In my project I use following API: https://justadudewhohacks.github.io/face-api.js/docs/index.html. The API is also correctly embedded in the project
My Project:
User upload a picture on a HTML page with input type:
<input class="chooseFile" type="file" id="preview">
Working: The project detect the faces in the uploaded picture
Not working: Project should recognize which person is on the uploaded picture
My Code so far (in script.js file) when I try to load my labeled images:
async function loadLabledImages() {
console.log("load labeled images");
let labels = ["BlackWidow", "CaptainAmerica", "CaptainMarvel",
"Hawkeye", "JimRhodes", "Thor", "TonyStark"];
return Promise.all(labels.map( async label => {
let descriptions = [];
for(let i = 1; i <= 2; i++) {
let filePath = `labeled_images/${label}/${i}.jpg`;
let imgAsBase64String = await imgToBase64(filePath);
let imgAsBlob = base64toBlob(imgAsBase64String, 'image/*');
let img = await faceapi.fetchImage(imgAsBlob);
let detections = await faceapi.detectSingleFace(img)
.withFaceLandmarks().withFaceDescriptor();
descriptions.push(detections.descriptor);
}
return new faceapi.LabledFaceDescriptors(label, descriptions);
}));
}
The labeled images are stored locally in the same directory.
The problem as far I know occurs on the faceapi.fetchImage(...) call.
When I run the HTML page with a Live Server I get following Error:
Failed to load resource: the server responded with a status of 404 (Not Found).
The network Header:
I also tried to store the folder labeled images on GitHub and to pass the link of the Github folder to the fetchImage function. I don't want the pictures to show on my HTML Page (just the uploaded picture).
Is there any solution how to use the fetchImage function with the locally stored images?

Using three.js: .glb 3d model shows up locally but not on github server, receive SyntaxError: Json.parse

I tried to use three.js to display a 3d model in my personal webpage. The model can be successfully displayed on my local server, however it failed to show up on my web server and I got an error like this:
(links to my .glb file, the main.js, and the index.html file)
I opened my browser web tools and the HTTP response data of my .glb model looks like this:
Any ideas would be highly appreciated.
BH
currently the main.js file looks like this:
$(document).ready(function(){
$nav = $('.nav');
$toggleCollapse = $('.toggle-collapse');
/** click event on toggle menu */
$toggleCollapse.click(function(){
$nav.toggleClass('collapse');
})
});
so it's hard to say exactly what the problem is now, but I'm guessing it was different before.
Without knowing the details of the server code [since you said it was fine in your local server but not on your main server] it's difficult to know the exact details of the issue, but one alternative for loading models without any server at all [but also works through servers] is by making another program [HTML file] that creates a JavaScript loadable file containing the data URL of the file loaded, which can then be included into the main HTML file with a standard script tag [or programmatically], then with the THREE.JS model loader, simply use the dataURL instead of the model URL.
I've persoanlly used this method many times without any server, not even a local server, and I've been able to load all kinds of models [and other files in general].
An example HTML file / code would look something like this:
BH
<br>
data URL-ifier
<br>
<input id="filePicker" type="file">
<br>
<div id="kinTayner"></div>
<script>
filePicker.onchange = () => {
var fr = new FileReader()
fr.onload = () => {
a = document.createElement("a")
kinTayner.innerHTML=""
a.download = filePicker.files[0].name+".html"//or .js,
//but .html files can actually be included in a
//project the same as JS scripts, which can be
//useful if you want to view it quickly in the
//browser
a.innerHTML = "Downlaod the DATA-Urlifier file?!"+
"<br>On GitHub might have to right click->save link as"
var id=Date.now()
a.href = URL.createObjectURL(new Blob([
`
/*BH
\n
<br>
Duel HTML and JavaScript File,
\n<br> can be opened in browser and
\n<br> included as a script, since JavaScript
\n<br>doesn't recognize HTML tags in comments,
\n<br> and JS comments don't affect HTML
<script>
if(!window.dataURLified) {
window.dataURLified = function(d) {
window._fileData_${id} = d;
//to access from console for later use
var m = document.getElementById("${id}")
if(!m) return;
m.innerHTML = "<h1>Your file data!</h1>"+
"<br><h2>"+d.name+"</h2><br>"+
"<a href='" + d.url +
"' target='_blank'>View your file [or right click to download]</a>"
}
}
</`+`script>
<div id="${id}"></div>
<style>
</style>
*/
//<script>
dataURLified({name:"` +
filePicker.files[0].name + `", url: "`+
fr.result
+`"})
// </`+`script>
`
], {type:"text/html"}))
kinTayner.appendChild(a)
}
fr.readAsDataURL(filePicker.files[0])
}
</script>
Then in your main code you can read it by including a script with that name [even if the extension is .html] and define a global function dataURLified [or whatever] to handle the data, here's an example file code [to be used after the above file is generated, and placed in the same directory as the following code, or hosted online, and in the input box enter the URL of that file and open the console]:
<h2>BH</h2><br>
<h3>HTML Fileized Loader</h3>
<input id="loader"> -- enter the name of the file you want to load as script [that was generated b4]
<script>
var files = []
function loadSc(name) {
return new Promise((r,j) => {
var sc = document.createElement("script")
sc.onload=()=>{
r({msg:"Loaded",fl:files[files.length-1]})
}
sc.onerror=(e)=>{
j({msg:"Nope",details:e})
}
sc.src=name;
document.body.appendChild(sc)
})
}
function dataURLified(d) {
//use it here
files.push(d)
}
///somewhere in code, can just call loadSc, just an example
loader.onchange = () => {
loadSc(loader.value)
.then(r=> {
console.log(myFile=r.fl,r.msg,"Use myFile.url for the path!")
}).catch(e=>{
console.log("PRoblem!",e)
})
}
</script>

Unable to upload & send an image to the server (ReactJS & JavaScript)

I am trying to include the option to upload an image in my app (React in the front side and NodeJS in the server one). The issue I am facing is that I am not able to send the file to the server. I saw other questions in this site and tutorials in other websites but I can't find what I'm doing wrong, so I hope you can, please, help me out.
This is part of my React code:
export default class DisplayPicture extends React.Component {
constructor(props) {
super(props);
// etc
}
onImageChange = (event) => {
if (event.target.files && event.target.files[0]) {
const img = event.target.files[0];
const formData = new FormData();
formData.append("image", img);
this.service
.uploadPicture(formData) // API call through a service
.then((backAnswer) => console.log(backAnswer))
.catch((err) => console.log(err));
}
};
render() {
return (
<div>
<p>Please, upload an image</p>
<input type="file" name="image" onChange={this.onImageChange} />
</div>
);
}
}
However, when I take a look at what the service sends to the server, it is an empty object and the server gets obviously the same in req.body and an "undefined" when looking for req.file.
I know the usual thing is to upload files by using a form, but I've already tried and got the same result, so I shared the shorter version.
Thanks in advance!!

Issue while printing pdf files from Blob angular

I have an Api that returns the data in the format of
{ fileName: string, blob: Blob }[]
I want to print all these files, so I am using
_files.forEach((_fileInfo) => {
const blobUrl = URL.createObjectURL(_fileInfo.blob);
const oWindow = window.open(blobUrl, "print");
oWindow.print();
oWindow.close();
});
this opens the multiple print windows, but in preview it shows blank documents.
but when i download all these files as a zip it downloads the correct PDF files.
// add files to zip
files.forEach((_fileInfo) => {
zip.file(_fileInfo.fileName, _fileInfo.blob);
});
// download and save
return zip.generateAsync({ type: "blob" }).then((content) => {
if (content) {
return saveAs(content, name);
}
});
What could be the issue,
is there any way to print all documents in a sequence without opening multiple windows?
Pdf file takes time to load thats why it was showing blank document, So i used print-js to solve this issue.
how to import
import * as printJS from "print-js";
how to use
const blobUrl = URL.createObjectURL(_fileInfo.blob);
printJS(blobUrl);
In case, you don't want to use printJS
I was facing the same issue but in my case I only have to deal with one file at a time. I solved it by putting the print function in a timeout block, so in your case this would be
setTimeout(function(){
oWindow.print();
}, 1000)
if this works then great, if not then you might also need to set the source of window equal to the 'blobUrl' that you created. This should be done after you come out of the loop.

How can I read file content with react-dropzone?

I'm trying to learn more about working with files for an upcoming project. Is there a way with react-dropzone that I can run a function when onDrop happens to change the contents of the files I'm uploading? For example, if I'm uploading a word doc that says "Hi everybody" how would I change the content to "Hi Dr. Nick"?
I've tried just accessing the data by using the filereader api after before attempting to make the changes. I tried using filereader right after the opening curly bracket of the async function and wasn't able to get it to work.
import React from 'react';
import Dropzone from 'react-dropzone';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
const FileUpload = ({
children, disableClick, channelId, mutate, style = {},
}) => (
<Dropzone
style={style}
className="ignore"
onDrop={async ([file]) => {
const response = await mutate({
variables: {
channelId,
file,
},
});
console.log(response);
}}
disableClick={disableClick}
>
{children}
</Dropzone>
);
const createFileMessageMutation = gql`
mutation($channelId: Int!, $file: File) {
createMessage(channelId: $channelId, file: $file)
}
`;
export default graphql(createFileMessageMutation)(FileUpload);
Any thoughts on how to access and modify the contents of the file are greatly appreciated! Thanks.
onDrop={async ([file]) => {
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsText(file);
}}
What you can do on frontend is to read file content and display it, all manipulations with file content should be done on server side. Push your file using ajax to your server with list of informations you want to change and use for example in nodeJS fs = require('fs')to make file modifications.
Also please visit this post i see that guys provided some solutions for your problem:
Is it possible to write data to file using only JavaScript?
and here is a fidlle taken from above link: http://jsfiddle.net/o4rhg1xe/1/
In Summary, you can read text file content using code i have provided and then use method from link to create Blob object with content you want and such file can be downlaoded by browser, (see fiddle)
Still in my opinion file modifications shoudl be moved to back-end side, ans i cant see no usecase to make them on frontend side.

Categories