Getting a file type from URL - javascript

I need To find out the file type from a url image located on my server without checking the extension, but I'm not sure how to do that without putting the image into an "input" like this:
<input type="file" id="upload_file" accept="image/*|audio/*|video/*"/>
<input type="submit" onclick="sumbit()"/>
<script type="text/javascript">
function sumbit(){
var file_Element = document.getElementById("upload_file")
alert(file_Element.files[0].type);
//alert: image/png
}
<script>
I understand that ".type" only work with a file object, so how do I turn the url image into an object like this image of google's logo: https://www.google.ca/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png.
Do I need to use a ajax/flilereader? if so, how?

Assuming your Content-Type HTTP headers are accurate, you can avoid downloading the whole file just to check the type by creating a HEAD request. Assuming you don't also need the whole file for something else, this could be a much-quicker operation, especially for large files.
Working Example:
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://crossorigin.me/http://placehold.it/350x150', true);
xhr.onload = function() {
var contentType = xhr.getResponseHeader('Content-Type');
console.log(contentType);
};
xhr.send();
Alternately, you can achieve a similar result with a regular GET request by calling abort on the AJAX request object before it loads the whole body (in any remotely recent browser anyway).
Alternate Working Example:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://crossorigin.me/http://placehold.it/350x150', true);
xhr.onreadystatechange = function() {
// Wait for header to become available.
var contentType = xhr.getResponseHeader('Content-Type');
if (contentType) {
// Stop downloading, the headers are all we need.
xhr.abort();
console.log(contentType);
}
};
xhr.send();

The accept attribute value is not valid. There should be comma , instead of pipe | character separating MIME types.
You can use change event to check File object .type
<input type="file" id="upload_file" accept="image/*,audio/*,video/*"/>
<input type="submit" onclick="submit()"/>
<script type="text/javascript">
var elem = document.getElementById("upload_file");
elem.onchange = function(e) {
console.log(e.target.files[0].type)
}
function submit() {
if (elem.files.length) {
console.log(elem.files[0].type)
} else {
alert("no files selected")
}
}
</script>

Use XHR to download the file, and then use the Blob api to determine the mime type:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
//Here's the type
console.log(xhr.response.type);
};
xhr.send();

Related

Ajax blob type recognition javascript

I'm using javascript to download multiple files from a webpage.
I'm using FileSaver.js to save the file and this method to download :
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}
};
xhr.send(null);
}
together I'm using it like that :
downloadFile(imgurl, function(blob) {
saveAs(blob, "image" + item + ".jpeg");
});
but the problem is im not sure what is the image/video type and the links arent specifying them. (cant take extention from url there's none)
My main issue is recognition between videos and images, probably mp4/png but I prefer being able to determine each file type so I can save it with its extention.
thanks in advance

Working with Computer Vision Thumbnails API repsonse data in JavaScript

I'm using the Microsoft Cognitive Computer Vision API (the thumbnails function).
I'm trying to use JavaScript and I cannot make sense of the response.
My entire HTML document with embedded JS code is as follows:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<button id="btn">Click here</button>
<p id="response">
<script type="text/javascript">
$('#btn').click(function () {
$.ajax({
url: "https://api.projectoxford.ai/vision/v1.0/generateThumbnail?width=100&height=100&smartCropping=true",
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "382f5abd65f74494935027f65a41a4bc");
},
type: "POST",
data: '{"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"}'
})
.done(function (response) {
$("#response").text(response);
})
.fail(function (error) {
$("#response").text(error);
});
});
</script>
</body>
</html>
The response I'm getting does not appear to be JSON, it look like this:
How can I work with the response from this API such that I get the image as a base 64 string that I can set to be the src on an image element.
It will end up being something like this but I do not know how to get the <base64string> bit.
<img src="data:image/png;base64,<base64string>">
I've tried everything in the api test console at https://dev.projectoxford.ai/docs/services/56f91f2d778daf23d8ec6739/operations/56f91f2e778daf14a499e1fb/console and it seems to work fine.
I think the problem is that jQuery converts the argument passed to .done into a string – not sure how to stop it doing that. You could try converting that string back to a binary object but that doesn't feel right or you could work out how to get the raw response from jQuery.
I tried this using XMLHttpRequest (which works):
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.response, typeof this.response);
var response = document.querySelector('#response');
var img = new Image();
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
response.appendChild(img);
}
}
xhr.open('POST', 'https://api.projectoxford.ai/vision/v1.0/generateThumbnail?width=5&height=5&smartCropping=true');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Ocp-Apim-Subscription-Key", "382f5abd65f74494935027f65a41a4bc");
xhr.responseType = 'blob';
xhr.send('{"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"}');
The response from the service is a binary JPEG image, indicated by the response header "Content-Type: image/jpeg".
For advice on how to encode this as base64, and display it, you could look to these related answers:
Base64 encoding
Displaying an image from a web-service

XMLHttpRequest does not send file

I want to upload a file trough a XMLHttpRequest. i have looked everywhere for examples and found quite a few. But i cant figer out what it is i am doing wrong. This is my code. The function is triggerd when a button is pressed. It not wrapped in from tags
function upl_kost() {
var url = "proces_data.php?ref=upload_kost";
var hr;
var file = document.getElementById("file_kost");
var formData = new FormData();
formData.append("upload", file.files[0]);
if (window.XMLHttpRequest) {
hr=new XMLHttpRequest();
} else {
hr=new ActiveXObject("Microsoft.XMLHTTP");
}
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "multipart/form-data");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(return_data);
}
}
hr.send(formData);
}
and this function catches it.
if($_GET['ref'] == 'upload_kost') {
var_dump($_FILES);
}
My problem is that the $_FILES stays empty. When i look at the file.files variable in the js its loaded with the data from the file that i am trying to upload.
Thanks!
Reduce your JavaScript down to minimum required for this, then add in some helpful messages you can look in your console for
function upl_kost() {
var xhr = new XMLHttpRequest(),
url = 'proces_data.php?ref=upload_kost',
fd = new FormData(),
elm = document.getElementById('file_kost');
// debug <input>
if (!elm)
console.warn('Element not found');
else if (!(elm instanceof HTMLInputElement))
console.warn('Element not an <input>');
else if (!elm.files || elm.files.length === 0)
console.warn('<input> has no files');
else
console.info('<input> looks okay');
// end debug <input>
fd.append('upload', elm.files[0]);
xhr.addEventListener('load', function () {
console.log('Response:', this.responseText);
});
xhr.open('POST', url);
xhr.send(fd);
}
If you're still having a problem, it may be server-side, e.g. are you performing a redirect before trying to access $_FILES?
Your problem is that you're setting the content type of the request
hr.setRequestHeader("Content-type", "multipart/form-data");
If you ever saw a multipart/formdata post you'll notice the content type header has a boundary
Content-Type: multipart/form-data; boundary=----webko2354645675756
which is missing from your code.
If you do not set the content type header the browser will correctly set it and the required boundary. This will allow the server to properly parse the request body.

Upload file after javascript processing, no ajax

I am attempting to process a user-uploaded file in javascript and then upload the file to the server. Once the processing is complete, I want the upload to work as it would have if I had not interrupted it with javascript. That is, I want to send a POST request to something like "receive_file.php" where the form validation, move_uploaded_file(), and a "successful upload" message to the user will occur. I have tried this in jquery, and I get an UPLOAD_ERR_NO_FILE from php:
function upload(file) {
var form = $("<form/>", {
enctype: "multipart/form-data",
method: "POST",
action: "/path/to/recieve_file.php"
});
form.append($("<input/>", {
type: "file",
name: "audio_file",
value: file
}));
form.submit();
}
As far as I can tell, its not possible to write to an input type="file", only read from it. Still haven't found a great answer for this one, but what I have settled on is overwriting the current document with the response from an ajax request like so:
var fd = new FormData();
fd.append("audio_file", file);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'recieve.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.open();
document.write(xhr.response); // just overwrite the whole current document with "recieve.php"
document.close();
}
};
xhr.send(fd);

get full html source code of page through ajax request through javascript

The javascript code will be launched from www.example.com through the url bar in google chrome so i cannot make use of jquery. My goal is to pass the full html source code of www.example.com/page.html to a variable in javascript when i launch the code in www.example.com. Is this possible? If so how? I know to get the current page source it's just document.documentElement.outerHTML but i'm not sure how i'd do this. I think it's possible by using responseText somewhere in the following code:
http.send(params);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://www.example.com/page.html",true);
xmlhttp.send();
data = ""
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
data = xhr.responseText
}
}
xhr.send();
function process(){
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
}
xhr.send();
}
this is how i run script from the address bar.. I do it all the time..
i create a bookmark like this
javascript:script=document.createElement('script');script.src='http://10.0.0.11/clear.js';document.getElementsByTagName('head')[0].appendChild(script); void(sss=1);
then i host the js file on my computer.. i use analogx simpleserver... then you can use a full page for your script

Categories