React Filepond Loading Initial Images Not Working - javascript

I'm having some trouble using Filepond for React. Currently, I want to preload a user's profile picture when the page is loaded. I have tried two different approaches but none have worked yet:
First, I try to use the server load option of Filepond like so:
<FilePond
ref={pond}
... other props here
files={[
{
source: this.props.user.id,
options: {
type: 'local'
}
}
]}
server={{
load: (userId, load) => {
fetch(fetchDomain + "/profiles/" + userId)
.then(res => res.blob())
.then(blob => {
console.log('blob is: ', blob)
return load
})
}
}}
/>
I fetch from my express backend which is running on the same domain and returns an s3 image URL. This leads to an infinite loading situation and a picture is never loaded. I kept making small changes to this trying to fix it, but was never able to get it to work. At some point when I was messing with the code it would finish loading, but the image would be gray/unavailable with no error messages.
Another approach I took was simply setting Files to an image URL and this didn't work either. Same result, a greyed out image that I can clear it by clicking the remove item button. I did notice, however, that if that URL was a base64 url it would actually load the image properly.
I've been debugging this for a few hours already. Is there something I am missing here?
I'm not sure if it's relevant, but the setup at the top of my file looks like:
import 'filepond/dist/filepond.min.css';
import CropperEditor from './Cropper';
import FilePondPluginFileValidateType from "filepond-plugin-file-validate-type";
import FilePondPluginImageExifOrientation from "filepond-plugin-image-exif-orientation";
import FilePondPluginImagePreview from "filepond-plugin-image-preview";
import FilePondPluginImageCrop from "filepond-plugin-image-crop";
import FilePondPluginImageResize from "filepond-plugin-image-resize";
import FilePondPluginImageTransform from "filepond-plugin-image-transform";
import FilePondPluginImageEdit from "filepond-plugin-image-edit";
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css';
const fetchDomain = process.env.NODE_ENV === 'production' ? process.env.REACT_APP_FETCH_DOMAIN_PROD : process.env.REACT_APP_FETCH_DOMAIN_DEV;
// Register the plugins for filepond
registerPlugin(
FilePondPluginFileValidateType,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview,
FilePondPluginImageCrop,
FilePondPluginImageResize,
FilePondPluginImageTransform,
FilePondPluginImageEdit,
);
const pond = React.createRef();
Here is a picture of what the component looks like when loading after I got rid of all the plugins apart from FilePondPluginImagePreview and use the first method:
It says undefined...
After further reading of the documentation I'm now confused about whether I should be loading or fetching.

I was understanding the load and fetch features of the server object incorrectly. I had to get the image URL before and then use fetch or load within the server object in order to get the file from that URL and then convert it to a blob format. This would also work with an external server endpoint being called within the load feature of the server object as I was trying to do initially, but you'd have to make sure the server returns a file, not a URL. Well, I guess it could return a URL but you'd then have to do another fetch on that URL and then convert it to blob.
The answer to this question is what I did essentially.
File Preview in React FilePond not showing up when setting initial file

Related

load method in THREE.FileLoader only gets the content of index.html

I've set up a very small browser project using create-js-app. I try to load a file called test.txt located in my src directory.
Following is the content of my main.js:
import * as THREE from 'three';
const loader = new THREE.FileLoader();
loader.load(
"test.txt",
function (data) {
console.log(data);
},
function (xhr) {
console.log(
"Loading file : " +
(xhr.loaded / xhr.total) * 100 +
"% loaded"
);
},
function (err) {
console.error(err);
}
);
When running my site in Chrome, I get the content of my index.html file instead of test.txt. I spent some time trying to understand this with no success.
I get this result no matter which file path I specify as first argument of loader.load(), I can even specify a file that is not existing.
Has anybody already faced this issue?
Thanks a lot.
Edit: I'm using Parcel as the bundler.
This issue comes down to internal details of create-js-app, and different web applications may host static resources (i.e. images and other assets that are not compiled source code) in different ways. But generally speaking, the src/ directory is not hosted/deployed/served on the website. If your application has the structure shown here then you probably want to put the .txt file into the public/ directory instead.
Requesting any file that cannot be found at the given URL might be giving you the index page instead, depending on how your site is set up by create-js-app.
I'm updating the answer above: I'm using Parcel. I fixed my project by adding this line:
url = require('test.txt')
The require function makes the browser import the txt file, and it returns the hashed url of the stored file. All I had to do next was to call
loader.load(url, ... )

Does 'onDidChangeTextDocument()' promise in VScode extension depend on the user's active window to start listening?

I'm a new developer and this is my first Stack Overflow post. I've tried to stick to the format as best as possible. It's a difficult issue for me to explain, so please let me know if there's any problems with this post!
Problem
I'm working on a vscode extension specifically built for Next.js applications and running into issues on an event listener for the onDidChangeText() method. I'm looking to capture data from a JSON file that will always be located in the root of the project (this is automatically generated/updated on each refresh of the test node server for the Next.js app).
Expected Results
The extension is able to look for updates on the file using onDidChangeText(). However, the issue I'm facing is on the initial run of the application. In order for the extension to start listening for changes to the JSON file, the user has to be in the JSON file. It's supposed to work no matter what file the user has opened in vscode. After the user visits the JSON file while the extension is on, it begins to work from every file in the Next.js project folder.
Reproducing this issue is difficult because it requires an extension, npm package, and a next.js demo app, but the general steps are below. If needed, I can provide code for the rest.
1. Start debug session
2. Open Next.js application
3. Run application in node dev
4. Do not open the root JSON file
What I've Tried
Console logs show we are not entering the onDidTextDocumentChange() block until the user opens the root JSON file.
File path to the root folder is correctly generated at all times, and prior to the promise being reached.
Is this potentially an async issue? Or is the method somehow dependent on the Active Window of the user to start looking for changes to that document?
Since the file is both created and updated automatically, we've tested for both, and neither are working until the user opens the root JSON file in their vscode.
Relevant code snippet (this will not work alone but I can provide the rest of the code if necessary. ).
export async function activate(context: vscode.ExtensionContext) {
console.log('Congratulations, your extension "Next Step" is now active!');
setupExtension();
const output = vscode.window.createOutputChannel('METRICS');
// this is getting the application's root folder filepath string from its uri
if (!vscode.workspace.workspaceFolders) {
return;
}
const rootFolderPath = vscode.workspace.workspaceFolders[0].uri.path;
// const vscode.workspace.workspaceFolders: readonly vscode.WorkspaceFolder[] | undefined;
// this gives us the fileName - we join the root folder URI with the file we are looking for, which is metrics.json
const fileName = path.join(rootFolderPath, '/metrics.json');
const generateMetrics = vscode.commands.registerCommand(
'extension.generateMetrics',
async () => {
console.log('Succesfully entered registerCommand');
toggle = true;
vscode.workspace.onDidChangeTextDocument(async (e) => {
if (toggle) {
console.log('Succesfully entered onDidChangeTextDocument');
if (e.document.uri.path === fileName) {
// name the command to be called on any file in the application
// this parses our fileName to an URI - we need to do this for when we run openTextDocument below
const fileUri = vscode.Uri.parse(fileName);
// open the file at the Uri path and get the text
const metricData = await vscode.workspace
.openTextDocument(fileUri)
.then((document) => {
return document.getText();
});
}
}
});
});
}
Solved this by adding an "openTextDocument" call inside the "registerCommand" block outside of the "onDidChangeTextDocument" function. This made the extension aware of the 'metrics.json' file without it being open in the user's IDE.

Encoding static imagery from public folder using getStaticProps in Next.js

Next.js lays out a pretty comprehensive way to get imagery from the /public/ folder (where the app has you store static assets). The pattern is to use fs from Node and do the fetch in getStaticProps.
My attempt:
export async function getStaticProps({ params, preview = false, previewData }) {
const cityData = dataFiltered.find( city => city.citySlug === params.slug )
const cityMapImagePath = path.join(process.cwd(), `/public/static-maps/${cityData.imgPath}`)
const cityMapImageRes = await fs.readFile(cityMapImagePath)
const cityMapImageProcessed = JSON.stringify(cityMapImageRes)
return {
props: {
preview,
cityData: cityData,
cityMapImage: cityMapImageProcessed
},
revalidate: 60,
};
}
This code works, but it returns a pretty weird response when I reference that object in my component:
<img src="{ "type":"Buffer", "data":[255,216,255,224,0,6,75,56,86,87,...] } />
My error has something to do with how I'm processing what fs gives me back. Do I need to encode my jpeg into base64 to get Next to use it? This answer suggests stringifying and then parsing (didn't work for me). Or maybe I need a full blown endpoint to do this? Next isn't very clear on how to get imagery from getStaticProps into the component above it - perhaps you know how?
All data that is returned from the getStaticProps needs to be JSON serializable, so yes, if you want to return image there , you need to base64 encode it (this can be a problem for big images).
The other solution (if the scenario permits it) is not to do it with getStaticProps rather load the image on demand in the front end, by hitting the API after the page has already loaded.
What I ended up doing for the fetch in getStaticProps:
export async function getStaticProps({ params, preview = false, previewData }) {
const cityData = dataFiltered.find( city => city.citySlug === params.slug )
const cityMapImagePath = path.join(process.cwd(), `/public/static-maps/${cityData.imgPath}`)
let cityMapImageRes, cityMapImageProcessed
try {
cityMapImageRes = await fs.readFile(cityMapImagePath)
cityMapImageProcessed = Buffer.from(cityMapImageRes).toString('base64')
} catch {
cityMapImageProcessed = null
}
return {
props: {
preview,
cityData: cityData,
cityMapImage: cityMapImageProcessed
},
revalidate: 60,
};
}
Also make sure up in the component, you are properly encoding your image source as base64 with the data:image/png;base64, prefix. This was a silly mistake that cost me an hour of debugging:
<img src={`data:image/png;base64,${cityMapImage}`} alt='Alt text here' />
Finally, also note that Next.js when used with Vercel will impose a hard, 50MB cap (compressed) on the serverless function used to process your page file request. If you're doing a [slug].js template, all the assets for EVERY page generated will count towards that cap. You'll hit it pretty fast on deploy, so double check yourself.

I want to load an in vue that has been by post request using flask and response is its path

I already have tried many methods available on StackOverflow. Most of them ask to use require.context that will load all images path and then use image path that I have got from post response.
But my problem lies here, I ask user to upload the Image then save it locally in assets folder, process the image and save output in assets folder.
This image name has to be unique, so I use uuid.uuid4() in python- which is completely random.
require.context cannot load my image path since it was not available at time when webpack was being complied, Hence the error - Cannot find module '../assets/9a5d60e2-4c2c-4fd9-a617-5dcdde4db6cc.jpg'.
<TwentyTwenty
:before="getImgUrl(resp['original'])"
:after="getImgUrl(resp['dreamed'])"
beforeLabel='Orignal'
afterLabel="Dreamed"
keyboardStep=0.01 />
getImgUrl(pet) {
var images = require.context('../assets/', false, /\.jpg$/)
return images('' + pet + ".jpg")
}
Once your Vue application is built, there is no assets folder. You cannot require / import anything that doesn't exist at bundle-time.
What you should be doing is have your Python app save the uploaded images into a location that is accessible via HTTP (eg static/uploads or as you've indicated, your Flask app root).
You then just use a plain old, regular URL to display the image in your Vue app, eg
# .env file
VUE_APP_API_BASE=http://localhost:8080
<TwentyTwenty
:before="`${apiBase}/${resp.original}.jpg`"
:after="`${apiBase}/${resp.dreamed}.jpg)`"
beforeLabel='Orignal'
afterLabel="Dreamed"
keyboardStep="0.01" />
data: () => ({
apiBase: process.env.VUA_APP_API_BASE, // get API base URL from .env
resp: {
// whatever
}
})

Silently print a PDF file using javascript

The thing I want to build is that by clicking a button I want to trigger the direct print of a PDF file, but without opening or viewing it.
I have PDF as blob file returned from fetch API.
I tried a lot of examples but don't know exactly how to do it
Some examples tried:
// In my case, I had only blobData from PDF, but you can ignore this and set fileURL directly if it is not yours.
const file = new Blob([blobData], { type: 'application/pdf' });
const fileURL = window.URL.createObjectURL(file);
// As the URL is dynamic, we must set src here, but if it's not, just leave it direct on the HTML.
// Also, be careful with React literals. If you do this in a <iframe> defined in JSX, it won't work
// as React will keep src property undefined.
window.frames["my-frame"].src = fileURL;
// Then print:
window.frames["my-frame"].print();
<iframe name="my-frame" id="my-frame" title="my-frame" style="display: none"></iframe>
Also tried library, Print.js: http://printjs.crabbly.com/.
Is there way to print the pdf without visually opening it to the user?
We should support only Chrome browser.
Can someone provide example how to do it in React, Redux application?
try this print-js and this is npm package
install npm package
npm install print-js --save
Add following code
import print from "print-js";
const fileURL = "someurl.com/document.pdf";
const handlePrint = (e) => {
e.preventDefault();
print(fileURL);
};
similar question is here

Categories

Resources