Javascript: Verify External Url Of An Image - javascript

Suppose i have EXTERNAL URL(not from my website) and i want to verify it to make sure this url is one from these files:- jpg, jpeg, gif, png and also is a correct image file (not any script file or php). Also if this is possible:- Check if the url of the image is working or not.
#jfriend00 ok so here is what i'am trying to do. I had maded html form and when people submit it, it will call to a javascript function which will verify if the url is an image. So here is my code. But it's not working. Please tell me what should i do from here?
<script type="text/javascript">
function vrfyImgURL() {
var x = document.forms["submitIMGurl"].elements["img_url"].value;
if(x.match('^http://.*/(.*?).(jpe?g|gif|png)$')){
var imgsrc = x;
var img = new Image();
img.onerror = function(){
alert("Can't Be Loaded");
return false;
}
img.onload = function(){
alert("Loaded Successfully");
return true;
}
img.src = imgsrc;
}else{
alert("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.");
return false;
}
}
</script>
<form action="http://www.example.com/current_page" enctype='multipart/form-data' method="post" onsubmit="return vrfyImgURL();" name="submitIMGurl">
<input type="text" value="http://" name="img_url" />
<input type="submit" value="Submit" />
</form>

Your code in this post is not a correct implementation of the function I gave you in the previous post and will not work for a number of reasons. You cannot return true/false from the onload, onerror handlers. Those are asychronous events and your vrfyImgURL function has already returned.
You really HAVE to use the code I put in that previous post. It works. Just use it. Don't modify it. You pass in a callback and that callback gets called with the validation check results. You have to use asynchronous programming to use this where the callback gets called with the result. You can't use straight sequential programming like you are trying to do. It is your modifications to my code that have made it stop working.
You can see the code I gave you previously work here:http://jsfiddle.net/jfriend00/qKtra/ and in the example, it's working with images from a variety of domains. It is not sensitive to the domain of the image and <img> tags are not restricted by domain.
To hook it up to your form submit, you can do this:
<form action="http://www.example.com/current_page" enctype='multipart/form-data' method="post" onsubmit="return formSubmit();" name="submitIMGurl">
<input type="text" value="http://" name="img_url" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function formSubmit() {
var url = document.forms["submitIMGurl"].elements["img_url"].value;
if (!checkURL(url)) {
alert("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.");
return(false);
}
testImage(url, function(testURL, result) {
if (result == "success") {
// you can submit the form now
document.forms["submitIMGurl"].submit();
} else if (result == "error") {
alert("The image URL does not point to an image or the correct type of image.");
} else {
alert("The image URL was not reachable. Check that the URL is correct.");
}
});
return(false); // can't submit the form yet, it will get sumbitted in the callback
}
function checkURL(url) {
return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
}
function testImage(url, callback, timeout) {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = new Image();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "error");
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "success");
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
callback(url, "timeout");
}, timeout);
}
</script>
If this were my interface, I would disable the form and put up a note that the image URL is being checked starting when testImage is called and ending when the callback is called.

Related

XHR abort doesn't stop file uploading

I've made an XHR-based file uploader with progressbar, and I would like to add a feature to cancel the upload before it fully uploaded.
The simlified code (runs after DOM ready):
var xhr;
$('#upload').click(function(){
var file = $('#file').get(0).files[0];
xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(event){
if (event.lengthComputable){
var percent = event.loaded / event.total;
$('#uploadpercent').html(Math.round(percent * 100) + "%");
}
};
xhr.abort = function(){
console.log('aborted');
};
xhr.onload = function(){
$('#uploadpercent').html("100%");
// ...
};
xhr.open("POST", "upload.php?filename=" + file.name);
xhr.send(file);
});
$('#cancel').click(function(){
xhr.abort();
});
After the xhr.abort() called, the abort event handler prints the 'aborted' to the console, but it doesn't do anything else. The progress bar doesn't stop, and after it finished, the entire file is uploaded. Tested on the latest Firefox and Chrome.
I can't figure out what is wrong with my code.
Edit:
I've tried the same with jQuery, the code:
(mostly from How can I upload files asynchronously?)
var jqXHR;
$('#upload').click(function(){
var file = $('#file').get(0).files[0];
jqXHR = $.ajax({
type : "POST",
url : "upload.php?filename=" + file.name,
data : file,
xhr: function(){
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload){
myXhr.upload.addEventListener('progress', function(event){
if (event.lengthComputable){
var percent = event.loaded / event.total;
$('#uploadpercent').html(Math.round(percent * 100) + "%");
}
}, false);
}
return myXhr;
},
success : function(response){
$('#uploadpercent').html("100%");
if (response.length > 0){
console.log(response);
}
},
error : function(_jqXHR, textStatus){
if (textStatus === "abort"){
console.log('aborted');
}
},
cache : false,
contentType : false,
processData : false
});
});
$('#cancel').click(function(){
jqXHR.abort();
});
To my surprise, this is working as expected. When the jqXHR.abort() called, the 'aborted' text also printed, the process stopped, and only part of the file have been uploaded.
The problem is I want to make my code independent of jquery in the future, and I don't understand yet why my code isn't working the same way.
Ok, I noticed that the event name is onabort. With the xhr.abort = ... line I overwrote the abort function. So the solution:
xhr.onabort = function(){...};
or
xhr.addEventListener("abort", function(){...});
I have been scouring the forums and found many solutions that fail miserably...except for Ivan Tsai's response.
The abort method will trigger error handlers on the server and the request object's abort event, but it will not stop the upload.
I have had no success stopping the upload from the server upon receiving the abort event. The following all fail:
request.pause();
request.socket.end();
request.connection.end();
request.destroy();
response.status(413).send(message);
response.end();
The only effective way I have found to stop the upload below is the HTMLFormElement.reset() method. Interestingly, calling the reset method of an input of type file will not work, but the single input can be wrapped in a singleton form element, such as the uploadForm below, to achieve the desired effect.
var formData = new FormData(uploadForm),
files = fileInput.files,
xhr;
if(files) {
for (var i = 0, stop = files.length; i < stop; i++) {
formData.append(files[i].name, files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', uploadForm.getAttribute('action'), true);
progressListener = xhr.upload.addEventListener("progress", progressHandler, true);
xhr.upload.addEventListener("abort", abortHandler, true);
xhr.send(formData);
}
abortButton.addEventListener(function(){
if(xhr){
xhr.abort();
}
uploadForm.reset();
});
You can also reload the page with window.location.reload() or you can switch to another page with window.location.href = UrlOfNewPage.
If this doesn't work, check if function you use to cancel the upload will be executed, for example with outputing something with console.log
I have the same problem.
XMLHttpRequest.abort() just stop notifying XMLHttpRequest.uplad.progress.
XMLHttpRequest.abort() can't stop Chrome(63.0.3239.132) uploading files.
I tried the formObject.reset() with upload 1G file and it works.
Network usage in windows task manager goes down to zero after calling formObject.reset().
<script>
function cancelUploadFile() {
document.getElementById("my_form").reset();
}
</script>
<form id="my_form" method="post" enctype="multipart/form-data">
<div class="w3-grey" style="height:24px;width:0%" hidden
id="progressBar"></div>
<input type="file" id="file1" name="file1">
<input type="submit" value="Upload" onclick="uploadFile()">
<input type="submit" value="Cancel" onclick="cancelUploadFile()">
</form>

how to pass Image data uri from javascript to php

I have a webpage which displays a chart. I had to generate a pdf of this chart. So I wrote this code to capture the chart as an image and put inside the pdf. I used html2canvas for this which generated a data uri for the image. Now I am stuck with this uri in javascript. The pdf code is a php script which needs this uri. How do I do this ?
The chart.php generates the chart and using html2canvas stores the image datatauri into localstorage.
CHART.PHP
<script>
//<![CDATA[
(function() {
window.onload = function(){
html2canvas(document.getElementById('chart'), {
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
console.log(canvas.toDataURL("image/png"));
window.localStorage.setItem("imgURL", canvas.toDataURL("image/png"));
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
//alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
};
})();
//]]>
</script>
<body>
<a href="pdfGen.php" id="download" >Report</a>
</body>
This is the php script which generates the pdf using fpdf library
pdfGen.php
<?php
/*$pdf = new FPDF();
$pdf->AddPage();
//over here I want to add the image from the chart.php page whose data url is now in the localstorage.
..more code to generate report
$pdf->output();*/
?>
How do i send the such a big uri to this php script ? Trying an ajax wont work as I need to redirect to this php page. Also sending the uri along in the url wont work either as the url becomes too large and goes beyond its capacity.
In your script :
<script>
document.getElementById('imageURL').value=canvas.toDataURL("image/png");
</script>
create a form in ur body with a report button and an hidden field for URL :
<body>
<form action="pdfGen.php" id="download" method="post">
<iput type="hidden" id="imageURL" name="imageURL"/>
<input type="submit" value="Report" name="submit"/>
</form>
</body>
In your php page - pdfGen.php
<?php
$imageURL = $_REQUEST['imageURL'];
?>
Hope it helps.
EDIT
<script>
//<![CDATA[
(function() {
window.onload = function(){
html2canvas(document.getElementById('chart'), {
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
console.log(canvas.toDataURL("image/png"));
document.getElementById('imageURL').value=this.src;
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
//alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
};
})();
//]]>
</script>
You can also creaate file from base64 and send it to server, like in this post (works from ie10 and all modern browsers)

get a file as a string using javascript

I have a HTML form to upload a file.
My goal is to submit the form, check that the file has XML extension and get the file as a String into a JavaScript variable.
Then, I want to send a POST request to the server using this String.
Any idea how I can do that?
My goal is to submit the form, check that the file has XML extension and get the file as a String into a JavaScript variable.
I don't think you really mean you want to submit the form (as in, send it to the server) at this stage.
Then, I want to send a POST request to the server using this String.
You can do that on browsers that support the File API, which is most modern ones but not IE8 or IE9. There's an example in this answer.
Basically, you get the File instance from your <input type="file"> element's files list, check its name, read it, and then post it:
Complete Example (source) (other than the POST bit, which I assume you know how to do):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<input type="file">
<button>Go</button>
<script>
(function() {
"use strict";
// Get our input element and our button; in this example there's
// just one of each, you'd narrow down these selectors of course
var inputElement = document.querySelector("input[type=file]"),
button = document.querySelector("button");
if (typeof FileReader !== 'function') {
alert("The file API isn't supported on this browser.");
inputElement.style.display = button.style.display = "none";
return;
}
if (!inputElement.files) {
alert("Odd, this browser has FileReader but no `files` property on the input element.");
inputElement.style.display = button.style.display = "none";
return;
}
button.addEventListener("click", function() {
var file, filename, reader, filedata;
// Does it have any files?
if (inputElement.files.length === 0) {
alert("No file chosen");
return;
}
// Get its first file
file = inputElement.files[0];
// Get its name in lower case
filename = file.name.toLowerCase();
// XML extension?
if (filename.substr(-4) !== ".xml") {
alert("Please only choose .xml files");
}
else {
// Yes, read it
reader = new FileReader();
reader.onload = function() {
// Get the file data, note that this happens asynchronously
filedata = reader.result;
// Send your POST with the data; here, we'll just dump it out
// as text
displayXml(filedata);
};
reader.readAsText(file); // or you can use readAsBinaryString
}
}, false);
function displayXml(xmlText) {
var pre = document.createElement('pre');
pre.innerHTML = xmlText.replace(/&/g, "&").replace(/</g, "<");
document.body.appendChild(pre);
}
})();
</script>
</body>
</html>

How to upload base64 image resource with dropzone?

I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.
// .../init.js
var myDropzone = new Dropzone("form.dropzone", {
autoProcessQueue: true
});
Once the client have finished his job, he just have to click a save button which call the save function :
// .../save.js
function save(myDocument) {
var file = {
name: 'Test',
src: myDocument,
};
console.log(myDocument);
myDropzone.addFile(file);
}
The console.log() correctly return me the content of my document
data:image/png;base64,iVBORw0KGgoAAAANS...
At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.
Here is my (standart dropzone) HTML form :
<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div>
<div class="fallback">
<input name="file" type="file" />
</div>
</form>
I got a Symfony2 controller who receive the post request.
// Get request
$request = $this->get('request');
// Get files
$files = $request->files;
// Upload
$do = $service->upload($files);
Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :
var_dump($files);
return
object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
["parameters":protected]=>
array(0) {
}
}
I think i don't setup correctly my var file in the save function.
I tryied to create JS image (var img = new Image() ...) but without any success.
Thanks for your help !
Finally i found a working solution without creating canvas :
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
And the save function :
function save(dataURI) {
var blob = dataURItoBlob(dataURI);
myDropzone.addFile(blob);
}
The file appears correctly in dropzone and is successfully uploaded.
I still have to work on the filename (my document is named "blob").
The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData
[EDIT] : I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzone
And you can use it like this :
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');
I can't comment currently and wanted to send this to you.
I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.
Dropzone.prototype.addFileName = function(file, name) {
file.name = name;
file.upload = {
progress: 0,
total: file.size,
bytesSent: 0
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, (function(_this) {
return function(error) {
if (error) {
file.accepted = false;
_this._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this.options.autoQueue) {
_this.enqueueFile(file);
}
}
return _this._updateMaxFilesReachedClass();
};
})(this));
};
If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) { potentially line 1110.
Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!
Hopefully someone finds this useful and doesn't need to recreate it!
1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"
This implies that you set autoProcessQueue: false and intercept the button click, to execute the saveFile() function.
$("#submitButton").click(function(e) {
// let the event not bubble up
e.preventDefault();
e.stopPropagation();
// process the uploads
myDropzone.processQueue();
});
2) check form action
Check that your form action="/upload" is routed correctly to your SF controller & action.
3) Example Code
You may find a full example over at the official Wiki
4) Ok, thanks to your comments, i understood the question better:
"How can i save my base64 image resource with dropzone?"
You need to embedd the image content as value
// base64 data
var dataURL = canvas.toDataURL();
// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));
// trigger submit of the form
document.forms["form1"].submit();
You might run into trouble doing this and might need to set the "origin-clean" flag to "true". see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements
how to save html5 canvas to server

Check file extension and alert user if isn't image file

I need help to add some line of code to check is file is image, to check extension. This is my code that I use for indicate progress of uploading images. I do that in php and user can't upload any file except .jpg .jpeg .gif and .png but he doesn't get a message that file isn't uploaded. When I add javascript code for progress upload, my php message taht i create doesn't display anymore.
This is my javascript
upload.js file code:
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('image_id');
var data = new FormData();
data.append('javascript', true);
if(fileInput.files[0].size > 1050000) {
document.getElementById("image_id").innerHTML = "Image too big (max 1Mb)";
alert('Fotografija koju želite dodati je veća od 1Mb!');
window.location="upload_images.php"
return false;
}
for (var i =0; i < fileInput.files.length; ++i) {
data.append('image', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + ' %'));
}
});
request.upload.addEventListener('load', function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Dodavanje slika nije bilo uspješno! Pokušajte ponovo.');
});
request.addEventListener('readystatechange', function(event) {
if (this.readyState == 4) {
if(this.status == 200) {
var links = document.getElementById('uploaded');
window.location="upload_images.php?success"
console.log(this.response);
} else {
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'upload_images.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
And this is my form for uploading file:
<div id="uploaded">
</div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input name="image" id="image_id" type="file" size="25" value="Odaberi sliku" />
<input type="submit" id="submit" value="Dodaj Foto"/>
</form>
</div>
<div class="upload_progress" id="upload_progress"></div>
I need in that javascript code also to check is file is image. To allow jpg, jpeg, png and gif extensions and block others. To alert user if he trying to upload other kind of file.
if (!fileInput.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i))
alert('not an image');
for Vue.js
if (filename.match(/.(jpg|jpeg)$/i)){
$('#modalimage').modal('show')
vm.downloadimage = result.data
}else{
const a = document.createElement('a')
a.setAttribute('href', result.data)
a.dispatchEvent(new MouseEvent("click", {'view': window, 'bubbles':
true, 'cancelable': true}))
}
Other accepted answers here were true at their time, but are decade old and are not perfect any more. For now use the below as the latest 2022 solution:
if (!fileInput.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i))
alert('not an image');
Longer Explanation:
For e.g: 'name.ijpg' is not image, but monkeyinsight's accepted old answer still return true. While the latest above solution works perfectly. See below:
console.log('name.ijpg'.match(/.(jpg|jpeg|png|gif)$/i)); // Old Solution
console.log('name.ijpg'.match(/\.(jpg|jpeg|png|gif)$/i)); // Correct Solution
console.log('name.jpg'.match(/\.(jpg|jpeg|png|gif)$/i)); // Correct Solution
style you give class name-jsp
"Choose file",input:true,icon:true,classButton:"btn",classInput:"input-large name-jsp"
at your jsp or html you give id="cekJpg"(at click upload file not choose file)
<input id="cekJpg" type="submit" class="btn btn-primary" value="Upload image">
at javascript
//if click button upload image with id="cekJpg"
$("#cekJpg").on('click', function (e) {
//get your format file
var nameImage = $(".name-jsp").val();
//cek format name with jpg or jpeg
if(nameImage.match(/jpg.*/)||nameImage.match(/jpeg.*/)){
//if format is same run form
}else{
//if with e.preventDefault not run form
e.preventDefault();
//give alert format file is wrong
window.alert("file format is not appropriate");
}
});

Categories

Resources