How can I read a stream from the api to display it in the src of an img tag ?
With this response I just want to display it in a <img src="myStream" />
My first error was to try to display a pdf file in an <img/> tag. I used an <iframe /> instead.
Also I had to use fetch to make the request and after use response.blob() :
const myFunctionToConvertHttpResponseToFileUrl = () => async {
const response = await fetch('myurl.com')
const myBlob = response.blob()
this.fileURL = URL.createObjectURL(myBlob);
}
And After in the html
<iframe :src="fileUrl" type="application/pdf" />
Related
Blob link is created, but the link returns 404 error
About this code; I am making markdown text editor, and am working on copy/paste image functionality, such as from screenshot. When paste action is made, this code should console.log blob url of a pasted image. But it looks like image doesn't exsists when I go to blob link.
What I did wrong for passing the image as blob?
code
import { useState } from 'react'
import { ReactMarkdown } from 'react-markdown/lib/react-markdown'
export default function Home() {
const [input, setInput] = useState('')
const handlePaste = async(e) => {
var items = e.clipboardData.items;
let image = [].slice.call(items).filter((obj)=> {
// Filter the image items only
return obj.type.indexOf('image') !== -1;
})
const item = image[0];
console.log(item)
// Get the blob of image
const blob = await item.getAsFile();
let blobURL = URL.createObjectURL(blob);
console.log(blobURL)
};
return (
<>
<textarea
name=""
id=""
cols="30"
rows="10"
value={input}
onPaste={handlePaste}
onChange={(e)=>setInput(e.target.value)}
/>
<ReactMarkdown childrenhow ={input}/>
</>
)
}
You can't "go to the link". You can access the blob as a File object, and you can use the object URL as e.g. the src attribute of an img tag within the same document. But the object URL stops referring to anything as soon as you leave the page.
I'm trying to access a Rest API to get access to an image URL within. Character.Portrait has the url and it prints successfully. But when I try to change
document.getElementById('portrait').style.backgroundImage
It returns an empty string. I just want to set the background image to the image at this URL in the JSON.
This is also my first question here, so I apologize if it's hard to read.
JS -
//Set the URL up. userKey will eventually be provided by a person. Using my own character for testing.//
const url = "https://xivapi.com/character/";
var userKey = "1814929"
var api_url = url + userKey;
console.log(api_url)
//This calls the function below to access the API//
getCharacter();
//This is the function that gets access to the API. //
async function getCharacter() {
const response = await fetch(api_url);
const character = await response.json();
//This is where I'm having difficulty.
//This does *NOT* change the backgroundImage property.
document.getElementById('portrait').style.backgroundImage = character.Character.Portrait;
console.log(document.getElementById('portrait').style.backgroundImage);
//This accurately prints the Avatar's URL
console.log(character.Character.Avatar);
//This accurately prints the Portrait URL.
console.log(character.Character.Portrait);
}
HTML
<body>
...
<main>
<h1 id="pageTitle">Main</h1>
<div id="content">
<div id="character">
<div id="portrait">
</div>
</div>
</div>
</main>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/pages/scripts/main.js"></script>
</body>
</html>
A CSS background-image value should be in the format:
url(site.com/someimage.png)
You are missing the url wrapper.
I have trying to request an image from an API and set the src of an img in my web page. The API returns a blob that represents a .png file. At this time, I'm requesting the image using the following:
const fetchResult = await fetch(imageApiUrl);
const resultBlob = await fetchResult.blob();
console.log(resultBlob);
In the console, I can see:
Blob {size: [some number], type: "image/png" }
So, I know that I have a result. I assume a blob. I now need to set this blob as the source of an img in my HTML, which looks like this:
<img id="profilePicture" alt="Profile Picture" height="250" width="250" />
I have this:
var profilePicture = document.getElementById('profilePicture');
How do I set the src of the profilePicture element to the blob?
You could use URL.createObjectURL in order to create a temporary URL that points to the in-memory image:
let url = URL.createObjectURL(resultBlob);
const img = document.getElementById('profilePicture');
img.src = url;
I wish to display an input element's selected image. Can this be performed on a local file, accessing the image client side, or would I need to upload the image to a server?
Here's my attempt in React. I can access the correct file name from the input element using inputElem.files[0].name. As soon as I am trying to set an image element to it, the broken image icon is displayed, and no error is surfaced.
const App = () => {
// state to keep track of img elements src. The default works fine.
const [imgSrc, setImgSrc] = useState('/images/test.jpg')
function handleImgUpload() {
const url = '/images/' + e.target.files[0].name
setImgSrc(url)
console.log(url) // /images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG
}
function handleImgLoadSuccess() {
console.log('image loaded!')
}
function handleImgLoadError() {
console.log('image not loaded')
}
return (
<div>
<div>
<label htmlFor="img">Select an image:</label>
<input
type="file"
id="img"
name="img"
accept="image/png, image/jpeg"
onChange={(e) => handleImgUpload(e)}
/>
</div>
<img
src={imgSrc}
alt="Your upload"
onLoad={handleImgLoadSuccess}
onError={handleImgLoadError}
/>
</div>
)
}
In the console, however, the url seems to be correct.
<img src="/images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG" height="100" width="200" alt="Input" class="jsx-855240488">
Hey – I see what you're trying to do, but it doesn't look like this will work. You need to create a new file reader.
const showTempImage = (e) => {
const file = e.target.files[0];
const img = document.createElement("img");
const reader = new FileReader();
reader.addEventListener('load', (e) => {
img.src = e.target.result;
});
reader.readAsDataURL(file);
// Append the img tag to the dom somewhere
}
This did the trick by creating a correct blob url.
const inputImg = e.target.files[0]
const url = URL.createObjectURL(inputImg)
// blob:http://localhost:3000/test-img.jpg
The resulting file stays in memory and needs to be removed in order to create memory leaks.
URL.revokeObjectURL(url)
This also seems to be accomplishable with FileReader, though there are differences.
I'm trying to use a weather api for a basic website and I'd like to use the icons too. The request works in both environments, but in my local environment I get an error for the icon
GET file://cdn.apixu.com/weather/64x64/night/116.png net::ERR_FILE_NOT_FOUND
I thought it was related to https but probably not since it's only the image that won't load.
const key = 'b7e1e81e6228412cbfe203819180104';
const url = `https://api.apixu.com/v1/current.json?key=${key}&q=auto:ip`
const main = document.getElementById('main');
$.getJSON( url, function(json) {
const loc = json.location;
const cur = json.current;
const condition = {text: cur.condition.text, icon: cur.condition.icon}
main.innerHTML = `<img src = ${condition.icon}><div>${condition.text}</div>`
}
so ${cur.condition.text} will display "partly cloudy" but the icon does not display. Any advice?
update: seems to be working fine with live-server.
It may be because the Cross-Origin Request Policy (CORS) may not allow it. Please make sure that you are allowed to access those resources.
https://enable-cors.org/ to read up more about CORS.
Secondly,
<img src = ${condition.icon}>
should be
<img src="${condition.icon}">
You are forgetting the quotation marks.
https://www.w3schools.com/tags/tag_img.asp - Read more on image tags.
Additionally use the code below:
Also add http: to image src like <img src=http:${condition.icon}>.
const key = 'b7e1e81e6228412cbfe203819180104';
const url = `https://api.apixu.com/v1/current.json?key=${key}&q=auto:ip`
const main = document.getElementById('main');
$.getJSON(url, function(json) {
const loc = json.location;
const cur = json.current;
const condition = {
text: cur.condition.text,
icon: cur.condition.icon
}
main.innerHTML = `<img src="http:${condition.icon}"><div>${condition.text}</div>`
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>
As icon return in JSON as protocol-relative URL (without the scheme) //url.
Locally it will use the file:// protocol and that assumes the resource you’re referring to is on the local machine, But it's not.
To avoid this issue locally add http: or https:to image src like <img src=http:${condition.icon}>.
const key = 'b7e1e81e6228412cbfe203819180104';
const url = `https://api.apixu.com/v1/current.json?key=${key}&q=auto:ip`
const main = document.getElementById('main');
$.getJSON(url, function(json) {
const loc = json.location;
const cur = json.current;
const condition = {
text: cur.condition.text,
icon: cur.condition.icon
}
main.innerHTML = `<img src =http:${condition.icon}><div>${condition.text}</div>`
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>