I have a website running VueJS at localhost:3000 which does some stuff to call this.nextImage().
methods:
// content //
async nextImage() {
console.log("In nextImage from App.vue"); // keeping track of location
try {
const response = await axios.get('http://localhost:5050/images');
console.log(response.data);
[how to make an image?]
} catch (error) {
console.error(error);
}
}
// content //
<template>
<!-- stuff -->
<div class="picture"><img :src="[what should go here?]" :alt="imageName"></div>
<!-- more stuff -->
<template
on localhost:5050 is an express server, which includes this:
const path = require('path')
// content //
app.get('/images', (req, res) => {
console.log("Express server: /images"); // tracking location
let imageName = 'myImage'
let imagePath = path.join(__dirname, '/images/' + imageName + '.jpeg')
res.sendFile(imagePath)
})
Logging the response.data gives
����JFIF���
!.%+!&8&+/1555$;#;4?.4514+$+44444444444444444444444444444444444444444444444444���"����B !1AQ2aq���"BR�����b�#3CSr���D��$%4����&1Q!Aa�2q�"��?�Z�UyEZL�>��ˀ��#�'G
��YU�U�$RlX�d<ǜ
(... abbreviated because I had too much code)
I need two pretty straightforward things:
The image to render properly
The name of the image
This was a pretty easy fix. I didn't actually need to send the file itself, just a link to the file (just app.send(imagePath)). When the client makes a GET call to the server, they get a url that can just be included in the img tag like so: <img source="imagePath">.
Related
In my NuxtJS application I has a folder with html pages, that can be added/deleted in any time from outside (/static/pages/page1.html, /static/pages/page2.html, ...) and I got a mapping to real uri's for this pages
{ '/foo': 'page1.html', '/bar': 'page2.html', ... }
I know I can use #nuxtjs/proxy, but it requires to rebuild an app every time mapping changes. I also know I can use nginx's rewrites for this, but changing it's config every time is painful too.
I also tried using 'pages/_.vue' file, read .html in component and place it's content to html using v-html, but files contains full html page (w/ scripts), and nuxt throw and error in this case, 'cos v-html don't allow using js (or maybe another reasons, which I can't understand)
How can I make dynamic proxy for this in NuxtJS?
For someone looking for answer for same question
Solve this by creating simple server middleware
in /pages_proxy/index.js:
const path = require('path');
const { Router } = require('express');
const express = require('express')
const app = express()
const router = Router()
router.get('*', async (req, res, next) => {
const pages = { '/foo/': 'page1.html', '/bar/': 'page2.html', ... }
const page = pages[req.path];
if (page) {
res.sendFile(path.join(__dirname, '../static/pages', page));
} else {
next();
}
});
app.use(router)
module.exports = app
in nuxt.config.js
serverMiddleware: {
'/': '~/pages_proxy'
},
I'm creating a simple Blog to exploring Sveltekit and how it works.
I created an endpoint to manage the Upload of an image, which is stored in a folder placed in the root folder (same level of src).
Now I'm trying to get this image and shows in the front end when the post is loaded.
It's pretty simple but I can't manage how to do it. In Nodejs normally I create an API to serve the image when is called like (ex. the API url is /api/v1/images/):
function get(req, res, next) {
...
var fileStream = fs.createReadStream(imagePath);
res.writeHead(200, { "Content-Type": "image/" + extensionName });
fileStream.pipe(res);
...
}
In the frontend I call it:
<img src={getImageFromBackend("example.jpg")} alt="Example" />
But in Sveltekit I can't do the same.
Any ideas?
Thanks
You should create another endpoint that serves the image. The endpoint will look like this:
import {promises as fs} from "fs";
export async function get() {
const asset = await fs.readFile("sample.jpg");
return {
headers: {
"Content-Type": "image/jpeg"
},
body: asset
};
}
Here is a example of an endpoint sending an image:
import {promises as fs} from 'fs'
export async function GET() {
const asset = await fs.readFile("sample.jpg")
return new Response(asset, {
headers: {
"Content-Type": "image/jpg"
}
})
}
I created a script that extracts photos in the gallery of a certain profile…
Using instagram-web-api
Unfortunately now it no longer works, instagram does not return the image of the media
This is the mistake:
ERR_BLOCKED_BY_RESPONSE
Instagram has changed it’s CORS policy recently? How I can fix?
for php; I changed my img src to this and it works like charm! Assume that $image is the instagram image cdn link came from instagram page:
'data:image/jpg;base64,'.base64_encode(file_get_contents($image))
EDIT FOR BETTER SOLUTION
I have also noticed that, this method is causing so much latency. So I have changed my approach and now using a proxy php file (also mentioned on somewhere on stackoverflow but I don't remember where it is)
This is my common proxy file content:
<?php
function ends_with( $haystack, $needle ) {
return substr($haystack, -strlen($needle))===$needle;
}
if (!in_array(ini_get('allow_url_fopen'), [1, 'on', 'true'])) {
die('PHP configuration change is required for image proxy: allow_url_fopen setting must be enabled!');
}
$url = isset($_GET['url']) ? $_GET['url'] : null;
if (!$url || substr($url, 0, 4) != 'http') {
die('Please, provide correct URL');
}
$parsed = parse_url($url);
if ((!ends_with($parsed['host'], 'cdninstagram.com') && !ends_with($parsed['host'], 'fbcdn.net')) || !ends_with($parsed['path'], 'jpg')) {
die('Please, provide correct URL');
}
// instagram only has jpeg images for now..
header("Content-type: image/jpeg");
readfile( $url );
?>
Then I have just converted all my instagram image links to this (also don't forget to use urlencode function on image links):
./proxyFile.php?url=https://www.....
It worked like charm and there is no latency anymore.
now 100% working.
You can try this.
corsDown
Using the Google translation vulnerability, it can display any image URL, with or without permission. All these processes are done by the visitor's IP and computer.
I have the same problem, when I try to load a Instagram's pictures url (I tried with 3 IP addresses), I see this on the console:
Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE
You can see it here, the Instagram image doesn't load (Actually, when I paste this url on google it works, but Instagram puts a timestamp on there pictures so, it's possible it won't work for you).
It's very recent, 3 days ago, it works with no issues.
<img src="https://scontent-cdt1-1.cdninstagram.com/v/t51.2885-19/s320x320/176283370_363930668352575_6367243109377325650_n.jpg?tp=1&_nc_ht=scontent-cdt1-1.cdninstagram.com&_nc_ohc=nC7FG1NNChYAX8wSL7_&edm=ABfd0MgBAAAA&ccb=7-4&oh=696d56547f87894c64f26613c9e44369&oe=60AF5A34&_nc_sid=7bff83">
The answer is as follows. You can use the imgproxy.php file. You can do it like this:
echo '<a href="' . $item->link . '" class="image" target="_blank">
<span style="background-image:url(imgproxy.php?url=' . urlencode($thumbnail) . ');"> </span>
</a>';
Using PHP
u can grab content of the image and show it in php file as an image by setting the header:
<?php
$img_ctn = file_get_contents("https://scontent-ber1-1.cdninstagram.com/v/......");
header('Content-type: image/png');
echo $img_ctn;
You can display the Image using Base64 encoded.
Base64 func based on #abubakar-ahmad answer.
JavaScript:
export const checkUserNameAndImage = (userName) => {
/* CALL THE API */
return new Promise((resolve, reject) => {
fetch(`/instagram`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ userName }),
})
.then(function (response) {
return response.text();
})
/* GET RES */
.then(function (data) {
const dataObject = JSON.parse(data);
/* CALL BASE64 FUCNTION */
toDataUrl(dataObject.pic, function (myBase64) {
/* INSERT TO THE OBEJECT BASE64 PROPERTY */
dataObject.picBase64 = myBase64;
/* RETURN THE OBJECT */
resolve(dataObject);
});
})
.catch(function (err) {
reject(err);
});
});
};
Base64 func:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.send();
}
Now, instead of using the original URL, use the picBase64 property:
<image src={data.picBase64)}/>
I have built a simple PHP based media proxy to minimize copy&paste.
https://github.com/skmachine/instagram-php-scraper#media-proxy-solving-cors-issue-neterr_blocked_by_response
Create mediaproxy.php file in web server public folder and pass instagram image urls to it.
<?php
use InstagramScraper\MediaProxy;
// use allowedReferersRegex to restrict other websites hotlinking images from your website
$proxy = new MediaProxy(['allowedReferersRegex' => "/(yourwebsite\.com|anotherallowedwebsite\.com)$/"]);
$proxy->handle($_GET, $_SERVER);
I was too lazy to do the suggested solutions and since i had a nodejs server sending me urls i just wrote new functions to get the images, convered them to base64 and sent them to my frontend. Yes it's slower and heavier but it gets the job done for me since i don't have a huge need for performance.
Fetch and return base64 from url snippet
const getBase64Image = async (url) => {
return new Promise((resolve, reject) => {
// Safety net so the entire up
// doesn't fucking crash
if (!url) {
resolve(null);
}
https
.get(url, (resp) => {
resp.setEncoding("base64");
body = "data:" + resp.headers["content-type"] + ";base64,";
resp.on("data", (data) => {
body += data;
});
resp.on("end", () => {
resolve(body);
});
})
.on("error", (e) => {
reject(e.message);
});
});
};
You don't need any external modules for this.
I've written a custom field for KeystoneJS's AdminUI which uses TinyMCE's editor.
KeystoneJS runs an Apollo GraphQL Server underneath and auto-generates mutations and queries based on your CMS schema. TinyMCE has the capability to enter custom hooks to upload images.
I'd like to be able to connect the two -- upload images from TinyMCE to KeystoneJS's server using GraphQL mutations.
For instance, in my setup I have an Image field in the CMS. KeystoneJS has a GraphQL mutation that will allow me to upload an image
createImage(data: ImageCreateInput): Image
where imageCreateInputis
type ImageCreateInput {file: Upload}
This tutorial has an explanation of how to upload images from Apollo Client to an Apollo Server (which KeystoneJS is running).
const UPLOAD_MUTATION = gql`
mutation submit($file: Upload!) {
submitAFile(file: $file) {
filename
mimetype
filesize
}
}
`;
return (
<form>
<Mutation mutation={UPLOAD_MUTATION} update={mutationComplete}>
{mutation => (
<input
type="file"
onChange={e => {
const [file] = e.target.files;
mutation({
variables: {
file
}
});
}}
/>
)}
</Mutation>
</form>
);
I'm a bit confused as to how to integrate this into TinyMCE, particularly since the example is based on using a form, and TinyMCE sends me the data encoded in -- as far as I can see -- Base64.
TinyMCE provides me the opportunity to specify a custom upload handler :
tinymce.init({
selector: 'textarea', // change this value according to your HTML
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'postAcceptor.php');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});
It seems that TinyMCE provides me with a blob, when, as far as I see, Apollo Client expects a file name. Do I just use blobInfo.filename ? Is there a better way to upload TinyMCE images to a GraphQL Apollo Server?
I've never done any image uploading with TinyMCE before.
I've never used this, too ... but I would try to use file_picker_callback.
In this demo you can see files[0] - I'm pretty sure you can insert here a upload mutation call with file as an argument. Result (url) pass to cb() (as in example).
Also adjust configuration as in this answer
I need to upload an image, and display it, as well as save it so that I don't lose it when I refresh the localhost. This needs to be done using an "Upload" button, which prompts for a file-selection.
I am using node.js and express for the server-side code.
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});