Image not rendering in my Admin application - javascript

I am creating a admin application where i want to display uploaded images of product stored in database. I have uploaded images as an object id in MongoDB. But the image container in admin app displays the number of images stored in database. But the images are not displayed. I tried using absolute URL too but that doesnot work either.
Here is my code to upload images:
{productPictures.length > 0
? productPictures.map((pic, index) => (
<div key={index}>{pic.name}</div>
))
: null}
<input
type="file"
name="productPictures"
onChange={handleProductPictures}
/>
Here is the code to display images:
<label className="key">Product Pictures</label>
<div style={{ display: "flex" }}>
{productDetails.productPictures.map((picture) => (
<div className="productImgContainer">
<img src={generatePublicUrl(picture.img)} alt="" />
</div>
))}
</div>
Generate URL function looks like this:
const api ='http://localhost:2000/'
// const api = 'http://192.168.0.104:2000/'
const generatePublicUrl = (fileName) => {
return `http://localhost:2000/src/uploads/products/${fileName}`;
}
export {
api,
generatePublicUrl
};
Function to save product in database:
const createProduct= (req, res) => {
const { name, price, description, category, quantity, createdBy } = req.body;
let productPictures = [];
if (req.files.length > 0) {
productPictures = req.files.map((file) => {
return { img: file.location };
});
}
const product = new Product({
name: name,
slug: slugify(name),
price,
quantity,
description,
productPictures,
category,
createdBy: req.user._id,
});
product.save((error, product) => {
if (error) return res.status(400).json({ error });
if (product) {
res.status(201).json({ product, files: req.files });
}
});
}
The uploaded images in program looks like this:
Open image here
But the page displays blank area and filename shows undefined when inspected.
Open image here

I believe you are trying to add a non-public path to the source.
you need to add the files to the public folder so you can call assets using the path , otherwise you can import the images and then add them to the src attribute
Edit 1:
return `http://localhost:2000/src/uploads/products/${fileName}`;
this will not work , you can't access what inside the src
the only folder you can access it is the public folder

Related

Dynamically import all images from a folder in Astro

I am working with Astro. The project uses quite a few images, and I want to simplify the way I currently add new images. My routes are like:
example.com/pictures/[collection]
( "[" and "]" stands for a dynamic route )
Allowing for example:
example.com/pictures/mixed-tecnique
example.com/pictures/graphite
example.com/pictures/acrylic
In the file pages/pictures/[collection].astro I want to do the following (or something similar):
---
import * as collections from "public/img/collections"
const { collection } = Astro.props
---
{collections[collection].map(imgSrc => <img src={imgSrc} />)}
So now, to have a new Collection route, I just have to create a new folder and drop the images there.
Is there any way to do something to reach the same result? Thanks in advance!!
There are a bunch of different ways to implement a feature like this but here is a simple example making use of the fast-glob library
public
pictures
mixed-technique
example.png
example.png
example.png
graphite
example.png
example.png
example.png
arcylic
example.png
example.png
example.png
// src/pages/pictures/[collection].astro
---
import fg from 'fast-glob';
export async function getStaticPaths() {
// get all collection folder paths: 'public/pictures/[collection]'
const collections: string[] = fg.sync('public/pictures/*', { onlyDirectories: true })
// Create a new route for every collection
return collections.map(collection => {
// Create Route
return {
params: {
// Return folder name of collection as dynamic parameter [collection]
collection: collection.split('/').pop()
},
props: {
// Return array of all image srcs in collection as prop 'images'
images: fg.sync(`${collection}/**/*.{png,jpg}`).map(img => img.replace('public/', '/'))
}
}
})
}
export interface Props {
images: string[];
}
const { collection } = Astro.params
const { images } = Astro.props
---
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
{ images.map(img => <img src={img}/>) }
</body>
</html>
Note: I used fast-glob instead of Astro.glob or import.meta.glob() because it can take a variable as an argument (makes this logic easier/more dynamic) and because it only returns an array of file/folder paths instead of also attempting to return file content

File preview not available on loading the images from server in file pond

[checkout the code snippet, i have tried
Please checkout the code i tried to fetch the images from the s3 bucket. Fetching is accomplished but unable to preview the fetched image.
<FilePond
style = {{marginTop:'10px'}}
files={files}
allowMultiple={true}
allowReorder={true}
onupdatefiles={setFiles}
imagePreviewHeight = "125px"
server={{
load: (source, load, error, progress, abort, headers) => {
var myRequest = new Request(source);
fetch(myRequest).then(function(response) {
response.blob().then(function(myBlob) {
load(myBlob);
});
});
},
process: null
}}
labelIdle='Drag & Drop your files or <span class="filepond--label-action">Browse</span>'
/>
]1

<Image source={require(" ")} /> not displaying correctly?

Im confused that my Image is not being displayed.
This works but its a bit too static. I need a dynamic profile-picture update when uploading a file.
import picture from "../../images/public/600bc441b2b2b62c542bd135profilepicture.jpg";
return(
<div>
<Image className={"profilepicture"} source={picture} alt={"pic"} />
</div>
)
So I implemented it with my Backend-Axios-Call like this:
const [mapimages, setMapImages] = useState(null);
useEffect(() => {
axios.get(API_BASE_URL + '/user/images', payload)
.then(function (response) {
if (response.status >= 200 && response.status < 300) {
const files = response.data.files[0];
const requireimg = require("../../images/public/" + files);
setMapImages(<Image source={requireimg} alt={"TEXT"} />);
} else {
alert("error getting images");
}
})
.catch(function (error) {
console.log("DOWNLOAD: " + error);
});
}, []);
return(
<div>
{mapimages}
</div>
)
Sadly I dont get the Images displayed. It shows the correct path to the File though.
This is the path in my image inspector:
<img alt="TEXT" class="profilepicture" source="/static/media/600bc441b2b2b62c542bd135profilepicture.8a22cb97.jpg">
and navigating
from
http://localhost:3000/#/profile
to
http://localhost:3000/static/media/600bc441b2b2b62c542bd135profilepicture.8a22cb97.jpg
also displays the Image.
I always get this:
I'm clueless because this previously worked. I just forgot to push it to git :(
You should try to replace "source" with "src" inside your image tag

React Open file dialog

I am trying to open a File Dialog Box with React, so that the user can select a folder and save the file in that particular folder, however I cannot manage to do that. My code looks like this at the moment:-
const exportToCSV = (csvData, fileName) => {
const ws = XLSX.utils.json_to_sheet(csvData);
const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] };
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const data = new Blob([excelBuffer], {type: fileType});
FileSaver.saveAs(data, fileName + fileExtension);
}
const openDialogWindow = () => {
// Open dialog here and get the folder name
exportToCSV(csvData, (folderName + fileName))
};
return (
<button
id="btnExportToCSV"
onClick={(e) => openDialogWindow()}
>
Export Tasks To Excel
</button>
)
so in my openDialogWindow, I would like to have the option to open the dialog box, and let the user select a folder that I can then attach to the pre-defined fileName. This will give the user the option to save the file in his chosen directory.
Is this possible?
Thanks for your help and time!

How to delete all images in a folder or the folder itself in firebase

I am trying to delete all the images from a folder in firebase, or delete the folder itself and all the images that way.
I have looked at the solution from MIKI: FirebaseStorage: How to Delete Directory
I cant get it to work.
The images are placed in the bookPictures folder under another folder with the ID of the book.
Folder structure looks like this:
Folderstructure in firebase
Here is my code:
this.deleteFolderContents(`/bookPictures/${id}`)
deleteFolderContents = (path) => {
const ref = firebase.storage().ref(path)
ref.listAll().then(dir => {
dir.items.forEach(fileRef => {
this.deleteFile(ref.fullPath, fileRef.name);
});
dir.prefixes.forEach(folderRef => {
this.deleteFolderContents(folderRef.fullPath);
})
})
.catch(error => {
console.log(error.message)
});
}
Update:
In the solution from MIKI he uses the deleteFile. I thought it was a firebase function. I logged the error:
_this.delete is not a function. (In '_this.delete(ref.fullPath, fileRef.name)', '_this.delete' is undefined)
How do i delete images ?

Categories

Resources