Video blob data is not posting using xhr - javascript

I am using rtcmulticonnection.js. I want to save the video on server. Here are two files "index.html" and "save.php".
request.open("POST", url); does not post the data
here the source file link
"https://github.com/muaz-khan/RTCMultiConnection/blob/master/v2.2.2/demos/audio-video-screen-sharing-recording.html"
index.html
document.getElementById('recordAudioVideo').onclick = function() {
var localVideoStream = rmc.streams.selectFirst({
video: true,
local: true
});
if (!localVideoStream) return;
var recordingSession = {
audio: true,
video: true
};
var button = this;
if (button.innerHTML == 'Record Audio/Video') {
button.innerHTML = 'Stop Recording Audio/Video';
// http://www.rtcmulticonnection.org/docs/startRecording/
localVideoStream.startRecording(recordingSession);
} else if (button.innerHTML == 'Stop Recording Audio/Video') {
// http://www.rtcmulticonnection.org/docs/stopRecording/
localVideoStream.stopRecording(function(blob) {
//alert('Audio blob size in bytes: ' + blob.audio.size);
//alert('Video blob size in bytes: ' + blob.video.size);
var fileType = 'video'; // or "audio"
var fileName = 'ABCDEF.webm'; // or "wav"
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
console.log(formData);
xhr('save.php', formData, function (fName) {
window.open(location.href + fName);
});
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open("POST", url);
request.send(data);
}
button.innerHTML = 'Record Audio/Video';
}, recordingSession);
}
save.php
<?php
// Muaz Khan - www.MuazKhan.com
// MIT License - https://www.webrtc-experiment.com/licence/
// Documentation - https://github.com/muaz-khan/WebRTC-Experiment/tree/master/RecordRTC
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = './'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
the problem is at
request.open("POST", url);
request.send(data);
request.open("POST", url); does not post the data.it does not call url(means save.php).because i have alert some text to see if save.php is called or not. so it does not show any alertbox on client.how can i solve this problem.Also it shows no error on posting.

Related

Can not send file from Controller Action to browser for download

I am sending a XMLHttpRequest to a MVC Controller and i am expecting to receive a file as a result.
When debugging with the browser i am getting a response that is ok , but i do not know why it is not as a file:
JS
window.submit=function () {
return new Promise((resolve, reject) => {
var form = document.getElementById("newTestForm");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var method = form.getAttribute('method');
var action = form.getAttribute('action');
xhr.open(method, action);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response); //response looks ok...but no file starts downloading
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
xhr.send(data);
});
}
Controller
[HttpPost]
[Route([Some Route])]
public async Task BenchAsync(object request)
{
try
{
string fileName = "results.txt";
object result = await service.RunAsync(request);
byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
this.Response.ContentType = "application/octet-stream";
this.Response.ContentLength = data.Length;
using(MemoryStream stream=new MemoryStream(data))
{
await stream.CopyToAsync(this.Response.Body);
}
}
catch (Exception ex)
{
throw;
}
}
I have solved it thanks to this Post
It seems i had to transform the response into a BLOB , create a download link and point it towards this blob and the created link in order to download the file.
So the function looks like :
window.submit= function () {
return new Promise((resolve, reject) => {
var form = document.getElementById("newTestForm");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var method = form.getAttribute('method');
var action = form.getAttribute('action');
xhr.open(method, action);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
var blob = new Blob([this.response], { type: 'image/pdf' });
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'mytext.txt';
a.click();
window.URL.revokeObjectURL(url);
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
xhr.send(data);
});
}
P.S i do not know what the type of the blob is named for txt but it works as well , given the right extension.

Can't upload large files using XHR and FormData

I have created simple script using XMLHttpRequest. It sends text and (optionally) file. It works but problem is that large files (above 50MB) are not accepted. I thought that problem was with PHP's upload_max_filesize or post_max_size but it doesn't (I set it up 512MB). I don't know what to do now... Any ideas?
function publishPost() {
if (!event) { event = window.event; }
event.preventDefault();
var data = new FormData();
data.append('SelectedFile', document.querySelector('#post input').files[0]);
var x = new XMLHttpRequest();
x.open('POST', 'upload.php', true);
x.setRequestHeader('TEXT', post.innerHTML);
x.onload = function() {
if (x.readyState == XMLHttpRequest.DONE) {
if (x.responseText == '1') {
location.reload();
} else {
alert('Error: ' + x.responseText);
}
}
}
x.send(data);
}
And PHP:
$text = strip_tags($_SERVER['HTTP_TEXT']);
$file = $_FILES['SelectedFile']['name'];
$info = pathinfo($file);
$uniqid = uniqid();
if (!empty($file)) {
$newfile = '../files/'.$uniqid.'.'.$info['extension'];
if (move_uploaded_file($_FILES['SelectedFile']['tmp_name'], $newfile)) {
$file = $uniqid.'.'.$info['extension'];
}
}
// Adding to Database
My error is Undefined index: SelectedFile

Direct upload string to s3 from bootstrap modal not working

I observed a very strange behavior. If I set a button from web to upload string to S3, it works fine. But if I set a button from web to bring up a bootstrap modal, then from this modal I set a button to upload the string, it doesn't work.
Frontend is like below in both cases. The difference is whether clicking to run function 'saveToAWS' from web or from modal as 2-step-process, the latter returns xhr.status as 0.
function saveToAWS() {
var file = new File([jsonStr], "file.json", { type: "application/json" });
var xhr = new XMLHttpRequest();
var fn=file.name;
var ft = file.type;
xhr.open("GET", "/sign_s3_save?file-name=" + fn + "&file-type=" + ft);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log('signiture returned')
save_file(file, response.signed_request, response.url);
}
else {
alert("Could not get signed URL.");
}
}
};
xhr.send();
}
function save_file(file, signed_request, url) {
var xhr = new XMLHttpRequest();
xhr.open('PUT', signed_request);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('200');
}
else {
alert('cannot upload file');
}
}
};
xhr.send(file);
}
Backend as Node.js, in order to get a signed URL:
app.get('/sign_s3_save', isLoggedIn, function (req, res) {
var fileName = req.query['file-name'];
var fileType = req.query['file-type'];
aws.config.update({ accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var ac = req.user._id;
var timenow = Date.now().toString();
var fileRename = ac + '/json/' + timenow + '.json';
var s3_params = {
Bucket: S3_BUCKET,
Key: fileRename,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function (err, data) {
if (err) {
console.log(err);
}
else {
var return_data = {
signed_request: data,
url: 'https://' + S3_BUCKET + '.s3.amazonaws.com/' + fileRename
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
Any suggestion, please?

How to save binary data of zip file in Javascript?

I am getting below response from AJAX respose:
this is response of zip file.
please let me know how to save this filename.zip in Javascript. Inside the ZIP there is PDF file.
MY code is like this:
$.ajax({
url: baseURLDownload + "/service/report-builder/generateReportContentPDF",
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.responseType = 'arraybuffer'
},
type: "POST",
data: JSON.stringify(parameter),
contentType: "application/json",
success: function(result) {
console.log("ssss->"+result);
var base64String = utf8_to_b64(result);
//window.open("data:application/zip;base64,"+base64String); // It will download pdf in zip
var zip = new JSZip();
zip.add("PDFReport.pdf", result);
content = zip.generate();
location.href="data:application/zip;base64," + content;
$.mobile.loading('hide');
},
error: function(xhr){
console.log("Request Status: " + xhr.status + " Status Text: " + xhr.statusText + " " + xhr.responseText);
$.mobile.loading('hide');
showAlert("Error occured. Unable to download Report", "Message", "OK");
}
});
RESPOSE Console.log("ssss->"+result);
PK��Q��F���������������/crt_pdf_10204725.pdf��uX\M�8|p�����݃�;w�#p �ܝBp��݂�;|C�ھ�w������=O���]]�%�N�����#+�reup����������Y������̉�J����3)� O��C����F�M�P�&�����rA�#��7T.��z(%h��x�x0�0Z�-i��%q�e�M�����i�"�c��-/��j��齔/ļL瞄�0� �� >�o��[��6 멆�n��s�$�
�#>˘ '��wT�� ���3�36DK�+�̓�t6 ��r��sA:���x�<>n������'U��RLqA+���ݺ�BM��:4ĞP�}���:�}ߣP����?F)�9-�W0���2�{x��#2v8N.$V�>X=/�+�c}���ּ�\y���\*�J\��
���90�T�L� 3p���*Sfj(���PWWz��O�s�9]&����iO|�9�;�5��ʘdW�cl% �%;����u���%[�5������Q]$��[L>���yXg�9��2+&,iFs�Q�����u򪠵�.�E(�>W��+��M ؟E������i|���k�k�c蟴CcG�j��4s|x �F1�}��Y��,29�0M=-O����m\L��y��^On^���\���u��a���F9:zc�Sy�-�g��fu�n�C�T:{
��4&/
��LM9�98�
�&Pnc�!��m�r�~��)74�04��0�0������M�~"��.ikjG��M�-
Finally I got answer of my question:
https://github.com/eligrey/Blob.js/
https://github.com/eligrey/FileSaver.js/
Here is the code:
var xhr = new XMLHttpRequest();
xhr.open("POST", baseURLDownload + "/service/report/QCPReport", true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// alert("Failed to download:" + xhr.status + "---" + xhr.statusText);
var blob = new Blob([xhr.response], {type: "octet/stream"});
var fileName = "QCPReport.zip";
saveAs(blob, fileName);
}
}
xhr.responseType = "arraybuffer";
xhr.send(JSON.stringify(QCPParameter));
No dependancy.
Compatible with IE 10,11, Chrome, FF and Safari:
function str2bytes (str) {
var bytes = new Uint8Array(str.length);
for (var i=0; i<str.length; i++) {
bytes[i] = str.charCodeAt(i);
}
return bytes;
}
var xhr = new XMLHttpRequest();
xhr.open("POST", baseURLDownload + "/service/report/QCPReport", true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// alert("Failed to download:" + xhr.status + "---" + xhr.statusText);
var blob = new Blob([str2bytes(xhr.response)], {type: "application/zip"});
var fileName = "QCPReport.zip";
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display:none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
}
xhr.responseType = "arraybuffer";
xhr.send(JSON.stringify(QCPParameter));
Axios implementation:
const url = 'https://www.example.com/download-zip'
// Payload, eg list of docs to zip
const payload = { documents: ['id1', 'id2', 'id3'] }
// Axios options
const axiosOptions = {
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json'
}
}
// Fetch data and save file
axios
.post(url, payload, axiosOptions)
.then((response) => {
const blob = new Blob([response.data], {
type: 'application/octet-stream'
})
const filename = 'download.zip'
saveAs(blob, filename)
})
.catch((e) => {
// Handle error
})
})
Note
saveAs is a function from file-saver package I've been using to handle saving the file.
For those of you using fetch, you can do this doing something like this.
fetch(url, config).
.then((response) => {
return response.arrayBuffer()
})
.then((data) => handleData(data))
In handleData, you will then instantiate the Blob object to handle the zip data.
Here is my Answer
you can avoid using blob and avoid using Filesaver.
This is how i wrote for one of my project using GET Method
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
xmlHttp.setRequestHeader("Content-type","application/json");
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.responseType= 'blob';
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
const downloadUrl = window.URL.createObjectURL(xmlHttp.response);
const link = document.createElement('a');
link.setAttribute('href', downloadUrl);
link.setAttribute('download', `filename.zip`);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(link.href);
document.body.removeChild(link);
}
}
xmlHttp.responseType = "arraybuffer";
xmlHttp.send();

Image name on download javascript

i need a JavaScript to download a group of images.
It should download some like this:
01.jpg
02.jpg
03.jpg....
but i get default file name:
5cEDZLQ.jpg
5Npv209.jpg
5FgtD69.jpg...
here my function to download:
function SaveToDisk(fileURL, fileName) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName;
var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
window.webkitURL.revokeObjectURL(save.href);
}
tried various ways, but always download with the default name
Well is a long time but here is the solve.
Dowload the image/file using XMLHttpRequest and pass the result to the function saveAs from FileSaver.js
Example:
var xhr = new XMLHttpRequest();
var url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/272px-Google_2015_logo.svg.png';
var name = 'Google Logo.png';
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onprogress = function(e) {
if (e.lengthComputable) {
console.log( ((e.loaded / e.total) * 100) + '%');
}
};
xhr.onload = function() {
if (this.status === 200) {
var file = this.response;
saveAs(file, name);
console.log('File Saved!!!')
}
};
xhr.onerror = function(e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
};
xhr.send();

Categories

Resources