I have the following server side code in web api
tempResponse = Request.CreateResponse(HttpStatusCode.OK);
tempResponse.Content = new StreamContent(stream);
tempResponse.Content.Headers.Add(#"Content-type", "application/pdf");
tempResponse.Content.Headers.ContentType = new
System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
tempResponse.Content.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("inline");
I am using angular JS and following is the code in my javascript file.
$http.post(apiURL + "/DownloadPdf", data, { responseType: 'arraybuffer'}, config)
.then(function (result) {
var file = new Blob([result.data], { type: 'application/pdf' })
var fileName = "CommissionStatement.pdf"
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.location.href = 'Assets/Document CheckList.pdf'
window.navigator.msSaveOrOpenBlob(file, fileName)
} else {
var objectUrl = URL.createObjectURL(file)
window.open(window.location.href = 'Assets/Document CheckList.pdf', '_blank')
window.open(objectUrl, '_blank')
$window.location.href =
window.location.protocol + "//" +
window.location.host + "?BrokerId=" +
AgentInfo.Data.BrokerId +
"&OfficeCode=" +
AgentInfo.Data.OfficeCode;
}
});
console.log($scope.Result)
},
function (error) {
$scope.Error = error.data
})
This blob opens fine in Google Chrome and FireFox. But IE will prompt for open or save. But I would like it to open in the browser. I would appreciate any input in making it open without prompting. Thanks
How about just excluding the if/else statement and just open the ObjectURL in IE as well? Otherwise pdf.js is a alternative if you want to render it in a browser using canvas
Another problem I see with your code is that you are trying to open up a new window with window.open() the problem is that they can become very easy blocked unless it happens within 1 sec after a user interaction event like onclick for example. A xhr.onload is not an user interaction event
So if you are experience some issue like that try doing something like
// Untested, just to give a ruffly idea
btn.onclick = () => {
var win = window.open('', '_blank')
win.document.body.innerHTML = 'loading...'
$http.post(...).then(res => {
var url = URL.createObjectURL(blob)
// redirect
win.location.href = url
})
}
Another thing. Why are you using responseType = arrayBuffer? you could set it to a blob directly...?
Related
I'm making a post to a WS and receive a PDF, I transform it into a blob, create a URL and open it.
If i'm opening the pdf in '_self', it works! I see the pdf.
I can also create a link with a download element and it works too!
But if i'm opening the pdf in '_blank', a new tab is created and instantly close.
Here is my code:
getDoc(id) {
const url = 'url';
this.$http.post(
url,
{
data: {
id,
},
},
{
responseType: 'arraybuffer',
}).then((response) => {
const blob = new Blob([response.data], { type: 'application/pdf;' });
const urlPdf = this.$window.URL.createObjectURL(blob);
const win = this.$window.open(urlPdf, '_blank');
win.focus();
});
}
Do I have to add something to allow it to open in a new tab/window?
Why does it works for _self but not _blank?
Thank you!
I had adblock enabled and this was the problem, once disabled the pdf is now working with _blank!
Thanks Alon Eitan for your comment!
I´m starting to customize/improve an old audio editor project. I can import audio tracks to my canvas VIA drag&drop from my computer. The thing is that I also would like to use audio tracks already stored in the server just clicking over a list of available tracks... instead of use the <input type="file"> tags. How can I read the server side files with a FileReader?Ajax perhaps? Thanks in advance.
This is the code for the file reader:
Player.prototype.loadFile = function(file, el) {
//console.log(file);
var reader = new FileReader,
fileTypes = ['audio/mpeg', 'audio/mp3', 'audio/wave', 'audio/wav'],
that = this;
if (fileTypes.indexOf(file.type) < 0) {
throw('Unsupported file format!');
}
reader.onloadend = function(e) {
if (e.target.readyState == FileReader.DONE) { // DONE == 2
$('.progress').children().width('100%');
var onsuccess = function(audioBuffer) {
$(el).trigger('Audiee:fileLoaded', [audioBuffer, file]);
},
onerror = function() {
// on error - show alert modal
var tpl = (_.template(AlertT))({
message: 'Error while loading the file ' + file.name + '.'
}),
$tpl = $(tpl);
$tpl.on('hide', function() { $tpl.remove() })
.modal(); // show the modal window
// hide the new track modal
$('#newTrackModal').modal('hide');
};
that.context.decodeAudioData(e.target.result, onsuccess, onerror);
}
};
// NOTE: Maybe move to different module...
reader.onprogress = function(e) {
if (e.lengthComputable) {
$progress = $('.progress', '#newTrackModal');
if ($progress.hasClass('hide'))
$progress.fadeIn('fast');
// show loading progress
var loaded = Math.floor(e.loaded / e.total * 100);
$progress.children().width(loaded + '%');
}
};
reader.readAsArrayBuffer(file);
};
return Player;
Thanks for the suggestion micronn, I managed to make a bypass without touch the original code. The code as follows is the following:
jQuery('.file_in_server').click(function()
{
var url=jQuery(this).attr('src');//Get the server path with the mp3/wav file
var filename = url.replace(/^.*[\\\/]/, '');
var path="http://localhost/test/audio/tracks/"+filename;
var file = new File([""], filename); //I need this hack because the original function recives a buffer as well as the file sent from the web form, so I need it to send at least the filename
var get_track = new XMLHttpRequest();
get_track.open('GET',path,true);
get_track.responseType="arraybuffer";
get_track.onload = function(e)
{
if (this.status == 200) //When OK
{
Audiee.Player.context.decodeAudioData(this.response,function(buffer){ //Process the audio toward a buffer
jQuery('#menu-view ul.nav').trigger('Audiee:fileLoaded', [buffer, file]); //Send the buffer & file hack to the loading function
},function(){
alert("Error opening file");
jQuery('#newTrackModal').modal('hide');
});
}
};
get_track.send();
});
After this, in the fileLoaded function, the track is added to the editor.
var name = 'Pista ' + Audiee.Collections.Tracks.getIndexCount();
track = new TrackM({buffer: audioBuffer, file: file, name: name}); //being audioBuffer my buffer, file the fake file and name the fake file name
Audiee.Collections.Tracks.add(track);
And... thats it!
If there is an img tag in a page whose final image it displays comes after a 302 redirect, is there a way with javascript to obtain what that final URL is after the redirect? Using javascript on img.src just gets the first URL (what's in the page), not what it was redirected to.
Here's a jsfiddle illustration: http://jsfiddle.net/jfriend00/Zp4zG/
No, this is not possible. src is an attribute and it does not change.
I know this question is old, and was already marked answered, but another question that I was trying to answer was marked as a duplicate of this, and I don't see any indication in any of the existing answers that you can get the true URL via the HTTP header. A simple example (assuming a single image tag on your page) would be something like this...
var req = new XMLHttpRequest();
req.onreadystatechange=function() {
if (req.readyState===4) {// && req.status===200) {
alert("actual url: " + req.responseURL);
}
}
req.open('GET', $('img').prop('src'), true);
req.send();
If you are open to using third party proxy this can be done. Obviously not a javascript solution This one uses the proxy service from cors-anywhere.herokuapp.com. Just adding this solution for people who are open to proxies and reluctant to implement this in backend.
Here is a fork of the original fiddle
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.ajax({
type: 'HEAD', //'GET'
url:document.getElementById("testImage").src,
success: function(data, textStatus, request){
alert(request.getResponseHeader('X-Final-Url'));
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('X-Final-Url'));
}
});
based on http://jsfiddle.net/jfriend00/Zp4zG, this snippets works in Firefox 17.0:
alert(document.getElementById("testImage").baseURI)
It doesn't work in Chrome. Not tested anything else-
Here is a workaround that I found out. But it works only if the image on the same domain otherwise you will get an empty string:
var img = document.getElementById("img");
getSrc(img.getAttribute("src"), function (realSrc) {
alert("Real src is: " + realSrc);
});
function getSrc(src, cb) {
var iframe = document.createElement("iframe"),
b = document.getElementsByTagName("body")[0];
iframe.src = src;
iframe.className = "hidden";
iframe.onload = function () {
var val;
try {
val = this.contentWindow.location.href;
} catch (e) {
val = "";
}
if (cb) {
cb(val);
}
b.removeChild(this);
};
b.appendChild(iframe);
}
http://jsfiddle.net/infous/53Layyhg/1/
I want to pass the input file from content page to extension background script, and then load it with FileReader() in the extension background script.
So in the web page I have a <input type="file"> and from onchange event I pass the file from content script to background page like this:
var myfile = document.getElementById('fileid').files[0];
chrome.runtime.sendMessage({myevent: "start", inputfile: myfile}, function(response) {});
in the background script I have this:
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.myevent==="start")
{
var reader = new FileReader();
reader.onload = function(e) {
// file is loaded
}
reader.readAsArrayBuffer(message.inputfile);
}
});
but FileReader not load it, I'm not sure if this is correct way , but all i need is to pass the input file element to background script and load it with FileReader to send it with HTTP POST from background script. Please tell me what is wrong or how to do it correctly. It will help a lot if I see a sample code, because I'm new to chrome extension development, and not so experienced.
All messages send through the Chrome extension messaging API MUST be JSON-serializable.
If you want to get the contents of a file at the background page, you'd better create a (temporary) URL for the File object, pass this URL to the background page and use XMLHttpRequest to grab its contents:
// Create URL
var url = URL.createObjectURL(myfile);
// Pass URL to background page (ommited for brevity) and load it..
var x = new XMLHttpRequest();
x.onload = function() {
var result = x.response;
// TODO: Use [object ArrayBuffer]
};
x.open('GET', url); // <-- blob:-url created in content script
x.responseType = 'arraybuffer';
x.send();
Though why do you want to send the file to the background page? Content scripts can also send cross-origin requests.
This works for chrome. You could find the whole production code here.
https://github.com/Leslie-Wong-H/BoostPic/tree/7513b3b8d67fc6f57718dc8b9ff1d5646ad03c75/BoostPic_Chrome/js
main.js:
// Crossbrowser support for URL
const URLObj = window.URL || webkitURL;
// Creates a DOMString containing a URL representing the object given in the parameter
// namely the original Blob
const blobUrl = URLObj.createObjectURL(imageBlob);
console.log(blobUrl);
chrome.runtime.sendMessage(blobUrl, (res) => {
imgUrl = res;
console.log(imgUrl);
clearInterval(refreshIntervalId);
// To prevent that it happens to halt at " Image uploading ..."
setTimeout(() => {
var imgUrlText = document.querySelector(imgUrlTextBoxId);
imgUrlText.value = imgUrl;
}, 1000);
// double check to clear interval to prevent infinite error loop of LoadingStateOne
// Hope it works.
setTimeout(() => {
clearInterval(refreshIntervalId);
}, 500);
console.log("Stop uploading state message");
background.js:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.startsWith("blob")) {
console.log("RECEIVED");
getBase64Url(request).then((res) => {
console.log("Arrived here");
// Acquired from https://stackoverflow.com/questions/18650168/convert-blob-to-base64/18650249#
const reader = new FileReader();
reader.readAsDataURL(res);
reader.onloadend = function () {
const base64data = reader.result;
console.log(base64data);
I'm currently writing an extension using Crossrider, and I need to load an image directly using the URL for doing some image processing on it. However, the onload event doesn't seem to be firing at all.
Am I doing something wrong or is it even possible to do that in a browser extension?
Here is the relevant piece of code:
var imga = document.createElement('img');
imga.src = obj.attr('href'); // URL of the image
imga.style.display = 'none';
imga.onload = function() {
alert('Image loaded');
var imgData = getImageData(imga, 0, imga.height - 3);
alert('Got Image data');
};
EDIT
Here is the full code
function readImage(obj)
{
console.log('Reading');
relayReadImage(obj.attr('href'));
}
function relayReadImage(link)
{
var dateObj = new Date();
var newlink = link + "?t=" + dateObj.getTime();
console.log(newlink);
appAPI.request.get(
{
url: newlink,
onSuccess: function(response, additionalInfo) {
console.log(response);
},
onFailure: function(httpCode) {
alert('GET:: Request failed. HTTP Code: ' + httpCode);
}
});
}
I'm a Crossrider employee and would be happy to help you. If I understand correctly, you are attempting to use the URL (href) of an object in a page's dom (obj.attr('href')) to load the image into a variable in the extension. You can achieve this using our cross-browser appAPI.request.get method in your extension.js file, as follows:
appAPI.ready(function($) {
appAPI.request.get({
url: obj.attr('href'),
onSuccess: function(response) {
var imgData = response;
console.log(imgData);
}
});
});
However, if I've misunderstood your question, please can you clarify the following:
What is the obj object is?
What are you trying to achieve, and in which context (in the Extension or on the Page)?