img src=blob: how to get the picture? - blob

I've an image displayed as blob:
<img id="imgcaptmobile" width="487" src="blob:http%3A//www.mysite.com/ab750f54-ecb4-4dc9-8d9d-4e28c4a41262">
How can I upload the picture as a file with jquery ajax please?...

Try this
var blobURL = "blob:http%3A//www.mysite.com/ab750f54-ecb4-4dc9-8d9d-4e28c4a41262";
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, image.width, image.height);
var picture = canvas.toDataURL("image/jpeg", 1.0);
var data = new FormData();
data.append("picture", picture);
$.ajax({
"url": "The Upload URL",
contentType: false,
processData: false,
type: 'POST',
"data": data,
success: function(response) {
//handle the response
}
});
}
image.src = blobURL;
<img src='blob:http%3A//www.mysite.com/ab750f54-ecb4-4dc9-8d9d-4e28c4a41262' />
and don't forget to decode the data from the server side ...

Related

How to sending DOM to Image in server(Vuejs)?

Please can anyone me show how to sending Base64 image into server,I am using Dom to image library.
//My script
import domtoimage from "dom-to-image";
export default {data: function() {return{ post: { image: "" },}
createPost(post) {
var node = document.getElementById("my-node");
domtoimage.toPng(node).then(function(dataUrl) {
var image = new Image();
image.src = dataUrl;
document.body.appendChild(image); }) this.$store.dispatch('createPost', post)},}
//In Action.js
createPost({commit}, post) {axios.post('posts', post).then(res => {commit('CREATE_POST', res.data)})},
imgProfile(event) {
this.image = event.target;
if (this.image.files && this.image.files[0]) {
var reader = new FileReader();
reader.onload = (e) => {
this.imageData = e.target.result;
}
reader.readAsDataURL(this.image.files[0]);
this.SvImage = this.image.files[0];
}
},

VueJs/Axios - Download pdf file in browser from API call

I am trying to download an pdf file using VueJs/Axios, but I get an empty file. The stream is 111 kb when created in C# but only 300 bytes when returned to Vue.js.
C#
HttpResponseMessage httpResponse = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
httpResponse.Content = new StreamContent(ms);
httpResponse.Content.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponse.Content.Headers.ContentDisposition.FileName = "test";
httpResponse.Content.Headers.ContentType = new
System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return httpResponse;
Vue.js
createPdf: function () {
var self = this;
self.ShowSpinner = true;
axios({
method: 'post',
url: self.baseUrl + '/api/ChangeRequestReport/CreatePdf',
responseType: 'blob',
data: {
model: self.ChangeRequestReportModel
}
})
.then(function (response) {
console.log(response);
//self.ChangeRequestReportModel = response.data;
const url = window.URL.createObjectURL(new Blob([response.data], { type: "application/pdf" }));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'test.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
self.ShowSpinner = false;
})
.catch(error => {
console.log(error);
this.error = true;
alert("error");
});

Always throws "network error" while do formdata post in react-native

in my react-native application i want to upload the image via api,Its working in postman but not in the app,Always gives me "network error"
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394)
at XMLHttpRequest.js:507
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:366)
at MessageQueue.js:106
at MessageQueue.__guard (MessageQueue.js:314)
at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)
profile.js
let formData = new FormData();
formData.append("file", {
name: response.fileName,
uri: response.uri,
type: response.type
});
formData.append("inputString", {
appversion: "2.0.0",
mobile: "456456456",
token: "1ba12dyrty452c4d6cb04544f52fccfc92748f"
});
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percentComplete = Math.ceil((e.loaded / e.total) * 100);
// here you will get the percentage of upload completed.
};
xhr.open("POST", "https://findmysalon.appspot.com/customer/uploadfile");
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
let resp = xhr.response;
var response = JSON.parse(resp);
console.log(response);
} else {
console.log(xhr.response);
console.log("error1");
//Response error
}
};
xhr.onerror = function() {
//ERROR
console.log("error2");
};
xhr.setRequestHeader("Authorization", "Basic dfgdfgdgddfg"); //eg: `Bearer ${token}`
xhr.send(formData);
You can use XMLHttpRequest()
eg:
let formData = new FormData();
let fileName = "image1.png";
formData.append("file", {
name: fileName,
uri: img.uri,
type: "image/png"
});
form.append("inputString", {
appversion: this.state.appversion,
mobile: this.state.mobile,
token: this.state.token
});
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percentComplete = Math.ceil((e.loaded / e.total) * 100);
// here you will get the percentage of upload completed.
};
xhr.open("POST", "https://fhy.appspot.com/customer/uploadfile");
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
let resp = xhr.response;
var response = JSON.parse(resp);
//Response success
} else {
//Response error
}
};
xhr.onerror = function() {
//ERROR
};
xhr.setRequestHeader("Authorization", "dfg dfgdfgdfgdfgdfg"); //eg: `Bearer ${token}`
xhr.send(formData);
try writing header as
headers: {
"Authorization", "dfg dfgdfgdfgdfgdfg";
"content-type", "multipart/form-data";
},

How can using JS to print a Byte array to local machine printer?

i have pdf's content in byte Array. I want a client way to print this pdf to local printer using js.
It is possible?
$http({
url: yourUrl,
method: 'GET',
headers: {
'Content-type': 'application/pdf'
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
var pdfFile = new Blob([data], {
type: 'application/pdf'
});
var pdfUrl = URL.createObjectURL(pdfFile);
var printwWindow = $window.open(pdfUrl);
printwWindow.print();
}).error(function (data, status, headers, config) {
alert('Sorry, something went wrong')
});
You need to open it in Browser window by a Blob first and call print function
i have not tested this code but hopfully it will work
var byteArray = yourDocumentBytes;
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
// This will check if the browser is IE
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))
{
var blob = new Blob(byteArray, { type: 'application/pdf' });
window.navigator.msSaveBlob(blob, documentName);
} else // If another browser
{
var element = document.createElement('a');
element.setAttribute('href', 'data:application/pdf;base64,' + encodeURIComponent(getBase64(byteArray)));
element.setAttribute('download', documentName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// and call print function like this
window.print()

How to read the POST data inside the template in JSREPORT

I have the following request to the jsreport engine:
$.ajax({
method: "POST",
contentType: "application/json",
dataType: "jsonp",
url: "http://localhost:5488/api/report",
data: {
template: {
shortid: "ry6HoQRee"
},
data: {
"D": "5"
}
},
success: function (s) {
window.open("data:application/pdf,base64," + escape(s.responseText));
},
error: function (s) {
console.log(s);
}
});
However I can't find a way to read it inside the report template:
<span>{{data.D}}</span>
How do I refer to the data object that is inside the POST body
jquery doesn't support binary responses like pdf. You should rather use XMLHttpRequest:
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:5488/api/report', true)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (this.status == 200) {
window.open("data:application/pdf;base64," + window.btoa(String.fromCharCode.apply(null, new Uint8Array(xhr.response))));
}
}
xhr.send(JSON.stringify({
template: {
shortid: 'Syeopu_xe'
},
data: {
'D': '5'
}
}))
Example of reaching data using handlebars templating engine
<span>{{D}}</span>
Additionally...
You may also take a look at jsreport official browser client library. It wraps the XmlHttpRequest calls into more elegant calls:
jsreport.serverUrl = 'http://localhost:3000';
var request = {
template: {
content: 'foo', engine: 'none', recipe: 'phantom-pdf'
}
};
//display report in the new tab
jsreport.render('_blank', request);
or in async fashion
jsreport.renderAsync(request).then(function(res) {
//open in new window
window.open(res.toDataURI())
//open download dialog
res.download('test.pdf')
});