window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("uploader-box"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
);
dataURL = canvas.toDataURL("image/png");
dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
$('#some_text_area_id').val(dataURL); // set the response in text area
// jQuery('#web_image').value(image);
jQuery.ajax({
url: "/my_controller/myaction",
type: "POST",
dataType: 'jsonp',
data: 'image_data='+dataURL,
cache: false,
beforeSend:function(){
},
success: function (response_data) {
},
error: function(response_data) {
}
});
In controller file i have written
data = params[:image_data]
file_obj=File.open("#{Rails.root}/public/images/test.png","wb") do |file|
file.write(Base64.decode64(params[:image_data]))
It gives
Errno::EACCES (Permission denied - test.png):
This error please some one help me. If any another way to save canvas data in ruby please tell me
Thanks,
Related
I create a simple website for Uploading files on Google Drive using Google Drive Api.
This is My Code :
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("Authorization", "Bearer" + " " + localStorage.getItem("accessToken"));
},
url: "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&fields=webViewLink",
data:{
uploadType:"media"
},
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
},
async: true,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
};
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
var progress_bar_id = "#progress-wrp";
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// update progressbars classes so it fits your code
$(progress_bar_id + " .progress-bar").css("width", +percent + "%");
$(progress_bar_id + " .status").text(percent + "%");
};
$("#upload").on("click", function (e) {
var file = $("#files")[0].files[0];
var upload = new Upload(file);
// maby check size or type here with upload.getSize() and upload.getType()
// execute upload
upload.doUpload();
});
});
Everything is Oky, But I just want to get the public URL of The files 😭 I just want to show the public url after file uploaded. Help Me Please
after upload the file and getting the fileId:
async function generatePublicUrl(fileId) {
try {
await drive.permissions.create({
fileId: fileId,
requestBody: {
role: "reader",
type: "anyone",
},
});
const result = await drive.files.get({
fileId: fileId,
fields: "webViewLink, webContentLink",
});
return result;
} catch (err) {
console.log(err);
}
}
and after doing that you just put your fileId in the format:
https://drive.google.com/file/d/"yourfileId"/preview
The Google Drive api does not have a method for creating the sharable link.
You will need to manually go to the Google drive website and create your sharable link there and store it in your system.
I have two blob file that recived from two recording method
window.recorderr = new MediaRecorder(stream, {
type:'video/mp4'
});
recorderr.start(99999999999999999);
window.recorder = new MediaRecorder(stream, {
type: 'video/mp4'
});
recorder.start(99999999999999999);
};
And i tried to save the file on a stop button click like this calling two events in a single click
btnStopRecording.onclick = function () {
stoprecordinguserstream();
stoprecordinglocalstream();
};
function stoprecordinguserstream()
{
if (!window.recorder) return;
recorder.ondataavailable = function (event) {
var blob = event.data;
var video = document.getElementById('recordedvideo');
video.src = URL.createObjectURL(event.data);
var formData = new FormData();
formData.append("MethodName", "saveuser");
formData.append("data", event.data);
$.ajax({
type: 'POST',
url: '/RecordSve.ashx',
data: formData,
processData: false,
contentType: false,
})
.done(function (data) {
console.log(data);
recordedsource = data;
});
console.log(blob.size, blob);
};
recorder.stop();
}
function stoprecordinglocalstream()
{
if (!window.recorderr) return;
recorder.ondataavailable = function (event) {
var blob = event.data;
var video = document.getElementById('recordedvideolocal');
video.src = URL.createObjectURL(event.data);
var formData = new FormData();
formData.append("MethodName", "saveclient");
formData.append("data", event.data);
$.ajax({
type: 'POST',
url: '/RecordSve.ashx',
data: formData,
processData: false,
contentType: false,
})
.done(function (data) {
console.log(data);
recordedsource = data;
});
console.log(blob.size, blob);
};
recorderr.stop();
}
but the above method only saving one file at a time how can i save two files in a single button click?
my handler function goes like this
public void ProcessRequest(HttpContext context)
{
MethodName = context.Request.Params["MethodName"];
switch (MethodName)
{
case"saveuser":
saveuservideo(context);
break;
case"saveclient":
saveclientvideo(context);
break;
default:
break;
}
}
The purpose of this is Iam trying to save video that recorded from a live session chat since i couldn't find any better way for saving it i tried to save it as two file as it is and merging the two files for a final output but Iam struggling to save multiple files at a time any help would be apreciated.
Here is how i over come the situvation using $.when()
$.when(stoprecordinguserstream(), stoprecordinglocalstream()).then(console.log('sucess'));
Sup guys, I got an issue about the ajax.
If I'm right, using ajax in synchronous way(async = false),
browser will be locked out while ajax is running.
So I timeouted the ajax like 1ms to show the loader first but here is the thing. My loader is based on svg file which is simple spinning image and even though I timeouted the ajax functions, when ajax started, whole image froze.
Is there any way to make the image move? I really need to make this work to
let the users know that something progressing.
thank you.
:) alright I edited it. I added some source code of it
javascript part:
function ajaxAddrInfo(result){
//console.log("결과 값");
//console.log(daum_local);
//console.log(result[0].bcode);
sigunCd = result[0].bcode.substring(0, 5);
dongCd = result[0].bcode.substring(5, 11);
bun = result[0].jibunAddress.bunji;
ji = result[0].jibunAddress.ho;
daum_local = "";
openBgOnly();
setTimeout(function(){
$.ajax({
url: './assets/php/detail.php',
type: 'post',
async: false,
data: {
S_CD: sigunCd,
D_CD: dongCd,
BUN: bun, JI: ji, FLR: fsum,
CNT: Bcnt,LCNT:Lcnt,
TYPE: "Building_Count"
},
success:function(data){
//console.log("working?");
var BcntRes = JSON.parse(data);
Bcnt = BcntRes['body']['totalCount'];
//showResult(resf);
},
error: function(error){
alert("BUILDING FLOOR SEARCH ERROR");
},
});//ajax ends.
},1);
//표제부
setTimeout(function(){
$.ajax({
url: './assets/php/detail.php',
type: 'post',
async: false,
data: {
S_CD: sigunCd,
D_CD: dongCd,
BUN: bun, JI: ji, FLR: fsum,
CNT: Bcnt,LCNT:Lcnt,
TYPE: "Building_Info"
},
success:function(data){
closeBg();
var res = JSON.parse(data);
BinfoRes = res;
var len = res['body']['totalCount'];
if(len === 0){
alert("건축물 데이터가 없습니다.");
}
else if(len === 1){
fsum = Number(res['body']['items']['item']['grndFlrCnt']);
fsum += Number(res['body']['items']['item']['ugrndFlrCnt']);
}
else{
//console.log(res);
fsum = Number(res['body']['items']['item']['grndFlrCnt']);
fsum += Number(res['body']['items']['item']['ugrndFlrCnt']);
//console.log(fsum);
}
//showResult(res);
//showResult(res);
$.ajax({
url: './assets/php/detail.php',
type: 'post',
async: false,
data: {
S_CD: sigunCd,
D_CD: dongCd,
BUN: bun, JI: ji, FLR: fsum,
CNT: Bcnt,LCNT:Lcnt,
TYPE: "Building_Level_Count"
},
success:function(data){
//console.log("working?");
//console.log(data);
LcntRes = JSON.parse(data);
Lcnt = LcntRes['body']['totalCount'];
//console.log(Lcnt);
//showResult(resf);
},
error: function(error){
alert("BUILDING FLOOR SEARCH ERROR");
},
complete:function(){
}
});
$.ajax({
url: './assets/php/detail.php',
type: 'post',
async: false,
data: {
S_CD: sigunCd,
D_CD: dongCd,
BUN: bun, JI: ji, FLR: fsum,
CNT: Bcnt,LCNT:Lcnt,
TYPE: "Building_Level_Info"
},
success:function(data){
//console.log("working?");
//console.log(data);
resfloor = JSON.parse(data);
//showResult(resf);
},
error: function(error){
alert("BUILDING FLOOR SEARCH ERROR");
},
complete:function(){
}
});
B_List(res);
},
error: function(error){
alert("BUILDING SEARCH ERROR");
},
complete:function(){
}
});
},1);
//층별
//setTimeout(closeLoading(),1500);
}
html part :
<div id="loading_background" class="text-center"><p id="loading_content"><img src="./assets/img/loader.svg" class="put-img-center"><h3>로딩중...</h3></p></div>
Hi Im trying to upload a 2 file or more, my problem is my progress bar will say 100% because of the small file being uploaded first, then its going back to the percent of the large file.. My question is how can I have a same progress if i have many files being uploaded?
for (var i = 0, f; f = files.files[i]; i++) {
$.ajax({
xhr: function(){
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
$('.bar').width(percent + '%');
}, true);
}
return xhr;
},
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: f,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer ACCESS TOKEN",
"Dropbox-API-Arg": '{"path": "/'+f.name+'", "mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
app.alert.show('success-message', {
level: 'success',
messages: 'your file has been upload to Dropbox',
autoClose: true
});
},
error: function (data) {
console.log(data);
}
})
}
I think you should store progress of each file in different variable (or maybe array of variables) and write function, that will update progressbar width when this vars are changed.
i'm trying encode the document generated in the attached code, but nothing happens, not generate error but neither encodes the file, and the ajax request is never executed
what is the correct way?
html2canvas(document.getElementById("workAreaModel"), {
onrendered: function(canvas)
{
var img = canvas.toDataURL("image/png");
var doc = new jsPDF("l", "pt", "letter");
doc.addImage(img, 'JPEG',20,20);
var fileEncode = btoa(doc.output());
$.ajax({
url: '/model/send',
data: fileEncode,
dataType: 'text',
processData: false,
contentType: false,
type: 'GET',
success: function (response) {
alter('Exit to send request');
},
error: function (jqXHR) {
alter('Failure to send request');
}
});
}
});
First, jsPDF is not native in javascript, make sure you have included proper source, and after having a peek on other references, I think you don't need btoa() function to convert doc.output(), just specify like this :
doc.output('datauri');
Second, base-64 encoded string is possible to contain ' + ' , ' / ' , ' = ', they are not URL safe characters , you need to replace them or you cannot deal with ajax .
However, in my own experience, depending on file's size, it's easy to be hell long ! before reaching the characters' length limit of GET method, encoded string will crash your web developer tool first, and debugging would be difficult.
My suggestion, according to your jquery code
processData: false,
contentType: false
It is common setting to send maybe File or Blob object,
just have a look on jsPDF, it is availible to convert your data to blob :
doc.output('blob');
so revise your code completely :
var img = canvas.toDataURL("image/png");
var doc = new jsPDF("l", "pt", "letter");
doc.addImage(img, 'JPEG',20,20);
var file = doc.output('blob');
var fd = new FormData(); // To carry on your data
fd.append('mypdf',file);
$.ajax({
url: '/model/send', //here is also a problem, depends on your
data: fd, //backend language, it may looks like '/model/send.php'
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
alter('Exit to send request');
},
error: function (jqXHR) {
alter('Failure to send request');
}
});
and if you are using php on your backend , you could have a look on your data information:
echo $_FILES['mypdf'];
This code is for capturing Html page from screen and save as Pdf and send to back end api As blob
const filename = 'form.pdf';
const thisData = this;
this.printElement = document.getElementById('content');
html2canvas(this.printElement).then(canvas => {
this.pdfData = new jsPDF ('p', 'mm', 'a4');
this.imageHeight = canvas.height * 208 / canvas.width;
this.pdfData.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 208, this.imageHeight);
this.pdfData.save(filename);
this.uploadFile(this.pdfData.output('blob'));
});
}
uploadFile(pdfFile: Blob) {
this.uploadService.uploadFile(pdfFile)
.subscribe(
(data: any) => {
if (data.responseCode === 200 ) {
//succesfully uploaded to back end server
}},
(error) => {
//error occured
}
)
}