I'm trying to use XMLHttpRequest to get image from a sharepoint library. But failed at the point of converting a weird string like
����JFIFS���E������..
back to image.
I managed to get a URL of my sharepoint files that when i put it in the browser, it will automatically download the image. I have also obtained the accessToken to gain permission to the files.
I tried to use base64 encoder from external script to convert the responseText and failed to display as image. Btw, the window.atob() or window.btoa() doesn't seems to do anything for my responseText.
I am not sure what kind of format i received from the responseText to be dealt with. Because i tried manually converting the image to base64 for testing, which begin like this
/9j/4AAQSkZJRgABAQAAAQABAAD/2wB..
. However, the string i got from using the the base64encoder i found online start like this
/f39/QAQSkZJRgABAQAAAQABAAD9/QBDAAs..
<div><img id="imgplaceholder" alt="place here"/></div>
<script>
var url =...;
var accessToken = ...;
var xhr = new XMLHttpRequest();
xhr.open("GET",url,true);
xhr.setRequestHeader("Accept","application/json; odata=verbose");
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var data = xhr.responseText;
//or var data = base64Encode(data);
document.getElementById("imgplaceholder").src = "data:image/jpeg;base64," + data;
}else{
alert(xhr.status + ":\n " + xhr.responseText);
}
}
</script>
I expect the image to be displayed in the , but nothing happens. I have tried using ajax too, but noting works. Please can someone help me?
I was following this https://sharepoint.stackexchange.com/questions/231251/fetch-and-display-image-from-sharepoint-list-javascript
Hope below script would be helpful for you.
<script type="text/javascript">
function Uint8ToBase64(u8Arr) {
var CHUNK_SIZE = 0x8000; //arbitrary number
var index = 0;
var length = u8Arr.length;
var result = '';
var slice;
while (index < length) {
slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length));
result += String.fromCharCode.apply(null, slice);
index += CHUNK_SIZE;
}
return btoa(result);
}
$(function () {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFileByServerRelativeUrl('" + _spPageContextInfo.siteServerRelativeUrl + "/MyDoc/panda.jpg')/openbinarystream";
var xhr = new window.XMLHttpRequest();
xhr.open("GET", url, true);
//Now set response type
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
var sampleBytes = new Uint8Array(xhr.response);
var imageBase64 = Uint8ToBase64(sampleBytes);
document.getElementById("imgplaceholder").src = "data:image/jpeg;base64," + imageBase64;
}
})
xhr.send();
})
</script>
<div><img id="imgplaceholder" alt="place here" /></div>
Related
I am trying to develop a component in Joomla 4. I have a simple button that should fire of a script to update the database.
I can make the call to the JavaScript ok, but the JavaScript does not appear to open the request URL, if anything it opens the current URL or refreshes the page. The script works fine outside of Joomla but not inside.
I have tried both the following, and the same thing happens:
*function buttonLike()
{
var xhr = new XMLHttpRequest();
var parentEl = this.parentElement;
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
console.log('Get Here OK' + parentEl.id);
xhr.open('GET', 'liked.php', true);
// Form data is sent appropriately as a POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function ()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var result = xhr.responseText;
console.log('Never Here Result: ' + result);
}
if(xhr.readyState == 4 && xhr.status == 0)
{
console.log('Always Here');
}
};
xhr.send("id=" + parentEl.id);
}*
OR
function buttonLike()
{
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
var request = new Ajax(url, {
method: 'post',
update: some_div,
data: options,
onComplete: function (){
$('some_field').setHTML('I am finished!');
}
}).request();
Been going round in circles on this one, any help would be appreciated.
Hello community I hope you can help me since I could not show a message to the user after downloading an excel file.
I am using httpRequest for sending data to the server and everything works correctly the file is downloaded but what I also want is to show the message.
Thank you very much for your help.
This is my code javaScript.
function download_excel_file() {
var file_name; //Example Test.xlsx
var parameter = '{file_name:"' + file_name + '"}';
var url = "Download.aspx/Download_File";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
var a;
if (xhr.readyState === 4 && xhr.status === 200) {
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response);
a.download = file_name;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Here I want to show the message with the legend = File downloaded successfully but it does not work.
$("[id*=message_download]").css("display","block");
$("[id*=message_download]").text(xhr.response.Text);
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.responseType = 'blob';
xhr.send(parameter);
}
<input id="btn_download_file" type="button" value="Download file" class="btn btn-success btn-block" onclick="return download_excel_file();"/>
<div id="message_download" class="p-3 mb-1 bg-secondary text-white text-center" style="display:none"> </div>
This is my code from server.
[WebMethod]
public static void Download_File(string file_name)
{
if (file_name != null || file_name != "")
{
string path = HttpContext.Current.Server.MapPath("~/Folder_Excel/" + file_name);
if (File.Exists(path))
{
// This is the message I want to show in the div $("[id*=message_download]")
HttpContext.Current.Response.Write("File downloaded successfully");
System.IO.FileStream fs = null;
fs = System.IO.File.Open(path, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=" + file_name);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(btFile);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
else
{
HttpContext.Current.Response.Write("No files");
}
}
}
Add an ‘alert’ at the end of the script:
<script>
function myFunction() {
alert("Success! File downloaded!");
}
</script>
added 2019 10 04
Use InnerHTML along with getElementById to set the message back from the server.
from https://www.w3schools.com/xml/xml_http.asp
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "filename", true);
xhttp.send();
You should display your message at first, then make the browser "click" on the download button. Otherwise the browser may just fire an unload event and stop executing any scripts at this time - like on redirection.
I don't think you're using the Attribute Contains Selector correctly.
$("[id*=message_download]").css("display","block");
$("[id*=message_download]").text(xhr.response.Text);
Try this instead:
$("[id*='message_download']").css("display","block");
$("[id*='message_download']").text(xhr.responseText);
Or better yet, use $("#message_download") Also notice that I changed xhr.response.Text to xhr.responseText
i have some problrm creating the radio buttons dynamically. in my problem i am requesting data from server in json formate than i check if it contains options i have to create the radio buttons otherwise simply creates the txt area of field to submit the answer. than again i parse it in json formate and send to the server and if my question is write i get new url for next question and so on...
my question is how can i create the radio buttons and read the data from it and than parse that data like {"answer": "something"}.my code is bellow:
enter code herefunction loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
var data = JSON.parse(this.responseText);
document.getElementById("my_test").innerHTML = data.question;
// Send the answer to next URL
if(data.alternatives !== null){
createRadioElement(div,);
}
var answerJSON = JSON.stringify({"answer":"2"});
sendAnswer(data.nextURL, answerJSON)
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function sendAnswer(url, data) {
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(this.responseText);
console.log(this.responseText);
loadDoc(data.nextURL);
}
}
// var data = JSON.stringify({"email":"hey#mail.com","password":"101010"});
xhr.send(data);
}
function createRadioElement(name, checked) {
var radioHtml = '<input type = "radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
I'm only guessing since you have some things in your posted code that won't even run, but createRadioElement returns a detached node which you never actually inject into your document.
E.g.,
document.body.appendChild(createRadioElement());
I have made a simple canvas and save it as an image. I have done this with the help of this code:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
and pop up the created image with this:
document.write('<img src="'+img+'"/>');
But its name is always a weird one. I want to rename the image name like faizan.jpg etc. How can I do this?
To put it simply, you can't. When you call the toDataURL method on an HTMLCanvasElement it generates a string representation of the image as a Data URL. Thus if you try to save the image, the browser gives it a default filename (e.g. Opera saves it as default.png if the Data URL was a png file).
Many workarounds exist. The simplest one is to make an AJAX call to a server, save the image on the server-side and return the URL of the saved image which can then be accessed and saved on the client-side:
function saveDataURL(canvas) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
window.location.href = request.responseText;
}
};
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.open("POST", "saveDataURL.php", true);
request.send("dataURL=" + canvas.toDataURL());
}
To save the image on the server side, use the following PHP script:
$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL)[1];
$decodedData = base64_decode($encodedData);
file_put_contents("images/faizan.png", $decodedData);
echo "http://example.com/images/faizan.png";
Got this working 100%! Just had to do a little debugging to the above answer. Here's the working code:
The JavaScript:
var saveDataURL = function(canvas) {
var dataURL = document.getElementById(canvas).toDataURL();
var params = "dataURL=" + encodeURIComponent(dataURL);
var request = new XMLHttpRequest();
request.open("POST", "/save-data-url.php", true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
window.console.log(dataURL);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
window.console.log(request.responseText);
}
};
request.send(params);
}
/scripts/save-data-url.php:
<?php
$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL);
$encodedData = $encodedData[1];
$decodedData = base64_decode($encodedData);
file_put_contents("images/log.txt", $encodedData);
file_put_contents("images/test.png", $decodedData);
echo "http://www.mywebsite.com/images/test.png";
?>
I just started using JSON and found this example from http://imdbapi.com/:
<script type="text/javascript">
// IMDb ID to Search
var imdbLink = "tt1285016";
// Send Request
var http = new ActiveXObject("Microsoft.XMLHTTP");
http.open("GET", "http://www.imdbapi.com/?i=" + imdbLink, false);
http.send(null);
// Response to JSON
var imdbData = http.responseText;
var imdbJSON = eval("(" + imdbData + ")");
// Returns Movie Title
alert(imdbJSON.Title);
</script>
But it just returns a blank page. What is wrong?
I'm sorry not to directly answer your question, but here is a jQuery version:
var imdbLink = "tt1285016";
// Send Request
$.getJSON("http://www.imdbapi.com/?i=" + imdbLink + "&callback=?", function(data) {
alert(JSON.stringify(data));
});
There are a couple possible issues with your code.
1.) ActiveX is IE only, not firefox, chrome, safari, etc.
2.) You have a cross-domain issue.
Example Fiddle