I working on a project where user capture photo from camera and show captured photo, but I want upload That Photo to server . How we can upload that image file to server. I am new please help me.
please help me how we upload image file to server. I tried much but can not upload successfully.
<html>
<head>
<title>NigraniSof</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
</head>
<body>
<button id="start-camera">Start Camera</button>
<video id="video" width="320" height="240" autoplay></video>
<button id="click-photo">Click Photo</button>
<div id="dataurl-container">
<canvas id="canvas" width="320" height="240"></canvas>
<div id="dataurl-header">Image Data URL</div>
<textarea id="dataurl" readonly></textarea>
</div>
<script>
let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let click_button = document.querySelector("#click-photo");
let canvas = document.querySelector("#canvas");
let dataurl = document.querySelector("#dataurl");
let dataurl_container = document.querySelector("#dataurl-container");
camera_button.addEventListener('click', async function() {
let stream = null;
try {
stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
}
catch(error) {
alert(error.message);
return;
}
video.srcObject = stream;
video.style.display = 'block';
camera_button.style.display = 'none';
click_button.style.display = 'block';
});
click_button.addEventListener('click', function() {
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
let image_data_url = canvas.toDataURL('image/jpeg');
dataurl.value = image_data_url;
dataurl_container.style.display = 'block';
});
</script>
</body>
</html>
you can add the canvas to an img tag for capturing and then you can take the image value using file reader method of javascript ,from that u will get the file blob which u can pass to php function using Ajax call. After that u can access that file blob in php which u can save to your server as well.
Related
i am making a meme api webpage
i want the webpage to display a new meme fetched from reddit using reddit api.
i have completed the api and it perfectly shows new memes on every refresh.
i want to embed these images in readme markdown as images
for that i am using
<img src="https://mywebpage.com/">
but i am not getting images when embedded in md.
Here is the code of my webpage-
index.html-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="script.js"></script>
</head>
<body>
<img src="loading.gif" id="meme" alt="meme didnt load :(" width="256px">
</body>
</html>
Script.js-
// function to fetch memes
function meme () {
let fetchRes = fetch("https://www.reddit.com/r/ProgrammerHumor/hot.json");
fetchRes.then(res => res.json()).then(d => {
// Generates a random number for the random meme
var randomNumber = Math.floor(Math.random() * 26)
// Actually gets the data from the api
var memeImg = d.data.children[randomNumber].data.url
var permalink = d.data.children[randomNumber].data.permalink
var postURL = `https://reddit.com${permalink}`
// setting the text to the data
document.getElementById('meme').src = memeImg;
})
}
// Reload page button
function reloadPage () {
document.location.reload(true)
}
// Calling the meme function
meme()
So I've put up this little test code modeling what's going on with the real version of what i have. In it I have set up 2 peer connections in the same file, each having a dedicated video element on the html. The problem is, when i start sharing the screen, the stream is not being shown on the other peer (peer2), which is the same problem I get in the real version of the code.
Here is the js code
'use strict';
const video1 = document.getElementById('video1');
const video2 = document.getElementById('video2');
let peer1 = new RTCPeerConnection();
let peer2 = new RTCPeerConnection();
peer1.onicecandidate = ev => {
console.log('peer1 oncandidate event');
if (ev.candidate) {
const c = new RTCIceCandidate(ev.candidate);
peer2.addIceCandidate(c);
}
};
peer2.onicecandidate = ev => {
console.log('peer2 oncandidate event');
if (ev.candidate) {
const c = new RTCIceCandidate(ev.candidate);
peer1.addIceCandidate(c);
}
};
peer2.onaddtrack = ev => addStreamSource;
function startVideoStream() {
const videoOptions = {
video: true,
audio: true
};
navigator.mediaDevices.getDisplayMedia(videoOptions)
.then(gotLocalMediaStream)
.catch(logError);
}
function gotLocalMediaStream(stream) {
console.log('setting the stream');
console.log(stream.getTracks());
peer1.addTrack(stream.getTracks()[0]);
video1.srcObject = stream;
peer1.createOffer()
.then(desc => {
peer1.setLocalDescription(desc);
peer2.setRemoteDescription(desc);
peer2.createAnswer()
.then(des => {
peer2.setLocalDescription(des);
peer1.setRemoteDescription(des);
})
.catch(logError);
})
.catch(logError);
}
function addStreamSource(event) {
console.log('ADDING STREAM SOURCE:');
video2.srcObject = event.streams[0];
}
function logError(e) {
console.error(`Bad thing: ${e}`);
}
function logSuccess() {
console.log('Promise Success!');
}
index.html
<html>
<head>
<title>Pretty cinema</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1 style="text-align:center;" id="text">
Pretty video streaming service
</h1>
<br />
<div id="vids">
<video id="video1" autoplay controls>
<source type='video/mp4' ; codecs="H.264" />
</video>
<video id="video2" autoplay controls>
<source type='video/mp4' ; codecs="H.264" />
</video>
</div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="./checking_peers.js"></script>
<div>
<div class="buttonsDiv">
<button onclick="startVideoStream()" type="button">Share</button>
</div>
</div>
</body>
</html>
important:
Already found the solution.
Simple explanation: I needed to create a MediaStream from the track received on peer2.
peer2.ontrack = event => {
const video = new MediaStream([event.track]);
video2.srcObject = video;
};
More details: The moment the two peers are connected (they've exchanged offer-answer's and ICE candidates) if you add a track on one end (peer1), the other end (peer2) is going to receive an event with the track in it if you've overriden the method ontrack of the peer2. You access the track as event.track. From that track you can create a MediaStream object by calling new MediaStream() and passing it an array of all tracks you want to base your stream on. That newly created stream can serve as the source for your video element, assign it with videoElement.srcObject = theMediaStream;.
Also: There was a problem with the way I set up the ICECandidate responses, so look closely into the code, it's written correctly here, might be you're having the same problem.
Code snippet below is a simplified example of an offline HTML video player I'm trying to develop.
The user is able to choose a video file, then this video file content is read into video player so user can play it.
The problem here is that the method I'm reading the video file with causes large memory leakage with large video files.
I'm using readAsDataURL, this is catastrophic in case of big files (e.g. for a ~200MB video file I get ~600MB webpage memory usage).
So, my question is, what's the most efficient way to read a local video file selected by user into my HTML video player?
I need a way that doesn't cause memory leakage like readAsDataURL does.
I think a direction to solution may be something that chunks local video files where only needed slices are loaded/unloaded to/from memory as needed like what happens with online videos. Also, a method that enables to read the video content directly from local hard disk instead of loading it to memory first as DataURL will be helpful.
Function responsible for passing selected video file as src:
function videoUpdateSource(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function() {
var videoTagElement_Exists = document.getElementById("loaded_video");
!videoTagElement_Exists ? videoElementInitiate() : videoRemoveSources();
videoAppendNewSource(reader.result);
}
}
Full test snippet:
function videoElementInitiate() {
var videoElement = document.createElement('video');
videoElement.setAttribute('id', 'loaded_video');
videoElement.setAttribute('width', '480');
videoElement.setAttribute('height', '300');
videoElement.setAttribute('controls', '');
document.getElementById("video_container").appendChild(videoElement);
videoTag = document.getElementById('loaded_video');
}
function videoUpdateSource(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function() {
var videoTagElement_Exists = document.getElementById("loaded_video");
!videoTagElement_Exists ? videoElementInitiate() : videoRemoveSources();
videoAppendNewSource(reader.result);
}
}
function videoRemoveSources() {
videoTag.pause();
var sourceElements = videoTag.getElementsByTagName('source');
for (var i = sourceElements.length - 1; i >= 0; --i) {
sourceElements[i].remove();
}
videoTag.removeAttribute('src');
}
function videoAppendNewSource(src) {
var source = document.createElement('source');
source.setAttribute('src', src);
videoTag.appendChild(source);
videoTag.load();
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<title>Offline Video Player</title>
</head>
<body>
<form>
<p>Select Video file in order to play</p>
<input type="file" id="fileElem" accept="video/*" onchange="videoUpdateSource(this.files[0])">
<label class="button" for="fileElem">Select video file</label>
</form>
<br/>
<div id='video_container'>
<!-- loaded video element to be placed here -->
</div>
</body>
</html>
Thanks to #AKX (comment) for suggesting a solution to use URL.createObjectURL instead of readAsDataURL.
Updating the function responsible for passing selected video file as src:
function videoUpdateSource(file) {
var url = URL.createObjectURL(file); // file is read as blob by default, check side note below.
var videoTagElement_Exists = document.getElementById("loaded_video");
!videoTagElement_Exists ? videoElementInitiate() : videoRemoveSources();
videoAppendNewSource(url);
}
Side Note:
A File object is a specific kind of a Blob, and can be used in any
context that a Blob can. In particular, FileReader,
URL.createObjectURL(), createImageBitmap(), and XMLHttpRequest.send()
accept both Blobs and Files.
Source
Now loading a 200MB or even 1GB video file results in ~60MB memory usage.
Updated code snippet:
function videoElementInitiate() {
var videoElement = document.createElement('video');
videoElement.setAttribute('id', 'loaded_video');
videoElement.setAttribute('width', '480');
videoElement.setAttribute('height', '300');
videoElement.setAttribute('controls', '');
document.getElementById("video_container").appendChild(videoElement);
videoTag = document.getElementById('loaded_video');
}
function videoUpdateSource(file) {
var url = URL.createObjectURL(file); // file is read as blob by default
var videoTagElement_Exists = document.getElementById("loaded_video");
!videoTagElement_Exists ? videoElementInitiate() : videoRemoveSources();
videoAppendNewSource(url);
}
function videoRemoveSources() {
videoTag.pause();
var sourceElements = videoTag.getElementsByTagName('source');
for (var i = sourceElements.length - 1; i >= 0; --i) {
sourceElements[i].remove();
}
videoTag.removeAttribute('src');
}
function videoAppendNewSource(src) {
var source = document.createElement('source');
source.setAttribute('src', src);
videoTag.appendChild(source);
videoTag.load();
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<title>Offline Video Player</title>
</head>
<body>
<form>
<p>Select Video file in order to play</p>
<input type="file" id="fileElem" accept="video/*" onchange="videoUpdateSource(this.files[0])">
<label class="button" for="fileElem">Select video file</label>
</form>
<br/>
<div id='video_container'>
<!-- loaded video element to be placed here -->
</div>
</body>
</html>
I'm trying to add javascript functionality that will return gps coordinates from exif data when the user clicks on a jpg displayed on the page. (Will use that to open a google map). I have managed to produce a working example when the script is inline in the html file, but not when trying to use a separate script file, getCoords.js
Found a similar question here: How to pass images from server to function in JavaScript?
What I'm trying to do is pass the src attribute from the html click event into the script. The script is getting the src, I can print that to the console and launch the jpg in devtools by clicking on the link in the console. But it doesn't seem to be even trying to run
EXIF.getData(my_image, function() {...
Here's the HTML:
<html lang="en">
<head>
<title>Map Test Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="styles.css" rel="stylesheet">
<script src="getCoords.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/exif-js/2.3.0/exif.min.js">
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBMLVQ6kCIfX4c8vVHa0qOf8P87DxCvt2w">
</script>
</head>
<body>
<picture>
<source media="(min-width: 750px)" srcset="images/van_from_erp2_L.jpg 2x, images/van_from_erp2_m.jpg 1x" />
<source media="(min-width: 450px)" srcset="images/van_from_erp2_m.jpg" />
<img src="images/van_from_erp2_s.jpg" id="hiking_0" alt="View of Vancouver from ridge" onclick='getCoords(src)'>
</picture>
<picture>
<source media="(min-width: 750px)" srcset="images/creek_1_l.jpg 2x, images/creek_1_m.jpg 1x" />
<source media="(min-width: 450px)" srcset="images/creek_1_m.jpg" />
<img src="images/creek_1_s.jpg" id="hiking_1" alt="forest creek image" onclick='Hello(id)'>
</picture>
<!--div id="map"></div-->
</body>
</html>
and here's the script:
function getCoords(source) {
console.log(source);
//pass image to EXIF.js to return EXIF data (EXIF.js sourced from github)
let my_image = new Image();
my_image.src = source;
console.log("hello from line 7");
EXIF.getData(my_image, function() {
console.log("Hello from line 9");
myData = this;
console.log(myData.exifdata);
// get latitude from exif data and calculate latitude decimal
var latDegree = myData.exifdata.GPSLatitude[0].numerator;
var latMinute = myData.exifdata.GPSLatitude[1].numerator;
var latSecond = myData.exifdata.GPSLatitude[2].numerator;
var latDirection = myData.exifdata.GPSLatitudeRef;
var latFinal = ConvertDMSToDD(latDegree, latMinute, latSecond, latDirection);
//console.log(latFinal);
// get longitude from exif data and calculate longitude decimal
var lonDegree = myData.exifdata.GPSLongitude[0].numerator;
var lonMinute = myData.exifdata.GPSLongitude[1].numerator;
var lonSecond = myData.exifdata.GPSLongitude[2].numerator;
var lonDirection = myData.exifdata.GPSLongitudeRef;
var lonFinal = ConvertDMSToDD(lonDegree, lonMinute, lonSecond, lonDirection);
//console.log(lonFinal);
let site = [latFinal, lonFinal];
console.log(site);
return(site);
// Create Google Maps link for the location
//document.getElementById('map-link').innerHTML = 'Google Maps';
});
//};
function ConvertDMSToDD(degrees, minutes, seconds, direction) {
var dd = degrees + (minutes/60) + (seconds/360000);
if (direction == "S" || direction == "W") {
dd = dd * -1;
}
return dd;
}
}
Put EXIF.getData(my_image, function() {...} inside the image onload function:
my_image.onload = function() {
EXIF.getData(my_image, function() {...}
}
Note that you have to wait for the image to be completely loaded,
before calling getData or any other function. It will silently fail
otherwise. Docs
Please have a look at the code below:
function longSentenceSpeak(text)
{
var url = "http://www.translate.google.com/translate_tts?tl=en&q="+finalString;
var url2 = "http://www.translate.google.com/translate_tts?tl=sp&q="+finalString;
var audio = document.getElementById('audio');
var source = document.getElementById('source');
source.src=url;
audio.load(); //call this to just preload the audio without playing
audio.play(); //call this to play the song right away
audio.onerror = function()
{
var url2 = "http://translate.google.com/translate_tts?tl=en&q="+text;
var audio = document.getElementById('audio');
var source = document.getElementById('source');
source.src = url2;
audio.load(); //call this to just preload the audio without playing
audio.play(); //call this to play the song right away
};
}
Below is my HTML:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="scripts/TTS.js"></script>
<script>
function longText()
{
longSentenceSpeak("hello world ");
}
</script>
</head>
<body>
<audio id="audio">
<source id="source" src="" type="audio/mp3" />
</audio>
<div><button onclick="longText()">Click me</button></div>
</body>
</html>
However this gives this error, even though it should handle it:
Failed to load resource: the server responded with a status of 404 (Not Found) (12:49:15:455 | error, network)
at http‍://www.translate.google.com/translate_tts?tl=en&q=hello
What I want to do is, if this error occurred, I want to use var url2 instead of var url in function longSentenceSpeak(text). How can I do this?
The error event doesn't bubble and in this case, it will fire on the <source> elements.
You thus need to listen to it from there:
function longText() {
var audio = document.getElementById('audio');
var source = document.getElementById('source');
source.src = '/foo.bar';
audio.load(); //call this to just preload the audio without playing
audio.play(); //call this to play the song right away
source.onerror = function() {
console.log('handling error event');
};
}
<audio id="audio">
<source id="source" src="" type="audio/mp3" />
</audio>
<div><button onclick="longText()">Click me</button></div>