I've some trouble into uploading a video to a form.
In my case, I need to upload some data with my video, so I left BackgroundUploader to use WinJS.xhr. But I can't figure it out how to convert my video file into something readable for my php.
My code:
var clickPicker = function () {
openPicker = Windows.Storage.Pickers.FileOpenPicker();
// We set the default location to the video library
openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.videosLibrary;
// Set de view to thumbnail
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
// Extension allowed to be taken
openPicker.fileTypeFilter.replaceAll([".mp4", ".avi"]);
openPicker.pickSingleFileAsync().done(function (file) {
uploadInit(file);
}, function (err) {
// MISTAAAAAAAAAAAAAAAAKEEEEEEEEE
console.log(err.message);
});
};
var uploadInit = function (file) {
// Creating the blob
var objectURL = window.URL.createObjectURL(file);
var url = "http://localhost/vdm_bo/videos/uploader";
var d = new Date();
var data = new FormData();
data.append("data[Video][pseudo]", 'H4mm3R');
data.append('data[Video][postal_code]', '67340');
// Converting date to a datetile mysql
data.append('data[Video][date]', ISODateString(d));
data.append('data[Video][age]', '24');
data.append("data[Video][email]", 'bliblu#hotmail.fr');
data.append("data[Video][question_selected]", 'qA');
data.append("data[Video][video_file]", file, file.name);
WinJS.xhr({
type: "POST",
url: url,
data: data
}).done(function (res) {
console.log('succes');
}, function (err) {
console.log(err.message);
}, function (res) {
});
};
So, to debug this I serialize the answer, and here is what I get :
When uploading with the file (without blob) :
s:36:"[object Windows.Storage.StorageFile]";
When uploading with blob (window.URL.createObjectURL(file))
s:41:"blob:9A06AB11-8609-42DC-B0A9-7FB416E70A9D";
And when I'm uploading the video just with my html form
a:5:{s:4:"name";s:36:"9147cb17e216d5182908ad370ff16914.mp4";s:4:"type";s:9:"video/mp4";s:8:"tmp_name";s:23:"C:\wamp\tmp\php13C8.tmp";s:5:"error";i:0;s:4:"size";i:26454182;}
Does anyone have a clue how to make it work ? Or maybe I do it all wrong and it's not the way I'm suppose to convert my file (It's the way to do for images, maybe not for video)
Okay, I found a way to do that. First ou need to get the file with getFileAsync() and not the Picker. Then you can create a blob with the stream of your file and add this blob to your form.
Here my code
var videosLibrary = Windows.Storage.KnownFolders.videosLibrary;
videosLibrary.getFileAsync(file.name).then(
function completeFile(file) {
return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
}).then(
function completeStream(stream) {
var d = new Date();
// Do processing.
var blob = MSApp.createBlobFromRandomAccessStream("video/mp4", stream);
var data = new FormData();
data.append("data[Video][pseudo]", 'H4mm3R');
data.append('data[Video][postal_code]', '67340');
// Converting date to a datetile mysql
data.append('data[Video][date]', ISODateString(d));
data.append('data[Video][age]', '24');
data.append("data[Video][email]", 'bliblu#hotmail.fr');
data.append("data[Video][question_selected]", 'qA');
data.append("data[Video][video_file]", blob, file.name);
return WinJS.xhr({ type: "POST", url: "http://localhost/vdm_bo/videos/uploader", data: data });
}).then(
function (request) {
console.log("uploaded file");
},
function (error) {
console.log("error uploading file");
});
Related
I have two audio files from RecordRTC both local & remote streams. Now I want to merge the two files into one file and upload it to the server via AJAX.
e.g. (audio1.webm) and (audio2.webm).
mediaRecorder.stopRecording(function() {
var blob = mediaRecorder.getBlob();
var fileName = getFileName('webm');
var fileObject = new File([blob], fileName, {
type: 'audio/webm'
});
var formData = new FormData();
formData.append('blob', fileObject);
formData.append('filename', fileObject.name);
$.ajax({
url: '{{ url('/') }}/save-audio',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(response) {
console.log(response);
}
});
});
Thank you in advance.
UPDATE:
I made it this way instead of recorder.addStreams, and still I can get the recorded.
var remoteVideos = $('#remoteVideos video');
var el = [];
$.each($('#remoteVideos video'), function(index, val) {
el[index] = val.srcObject;
});
el.push(stream);
multiMediaRecorder = new MultiStreamRecorder(el);
You can use a similar library: MediaStreamRecorder. Then use MultiStreamRecorder and pass two streams as below,
recorder = new MultiStreamRecorder([localStream, remoteStream]);
You will get localStream from getUserMedia and remoteStream from onaddstream event listener.
You may want to just pass the audio tracks in the array. The rest of the things as it is. FFmpeg and file merging is not necessary.
I got it now by doing this, as below;
function onMediaSuccess(localStream) {
var remoteVideos = $('#remoteVideos video')[0];
multiMediaRecorder = new MultiStreamRecorder([localStream, remoteVideos.srcObject]);
multiMediaRecorder.ondataavailable = function (blob) {
// POST/PUT "Blob" using FormData/XHR2
var blobURL = URL.createObjectURL(blob);
console.log(blobURL);
};
multiMediaRecorder.start();
}
But now there's another problem, ondataavailable is called twice but the first video is playable and working properly, while the second video is playable but (less than one second) I think it might be corrupted.
Cheers!
I have a node.js server, which uses express-fileupload to accept images. Now I'm working on the function to upload an image. But I don't want to use < form > since I prefer xhtml request for various reasons, but mainly because I don't want to redirect the user, after he uploads an image.
I have tried reading the picture as dataURI, sending it to the server, decoding it and writing it to a file, which didnt work and seemed to resource intensive and laborious.
//I used the dataString from the callback method and wrote it to a file using fs.writeFile
function dataURItoimage(dataString, callback){
const atob = require("atob");
dataString.replace("data:image/jpeg;base64,", "");
dataString.replace("data:image/png;base64,", "");
atob(dataString);
callback(null, dataString);
}
//User side code
avatarInput.addEventListener("change", (e) => {
const reader = new FileReader();
reader.readAsDataURL(avatarInput.files[0]);
reader.onload = () => {
avatar = reader.result;
tosend.avatar = reader.result;
}
}, false);
uploadButton.onclick = () => {
var request = new XMLHttpRequest();
request.open("POST", "/avatarUpload");
request.setRequestHeader("Content-Type", "application/json");
var tosend = {avatar: ""};
tosend.avatar = avatar;
request.send(JSON.stringify(tosend));
}
Is there a better way to upload an image, which the user can select, to a node.js server?
You can try this example. It worked for me. I hope it can help you.
Sending dataURL throw Ajax request:
const dataURL = snapshotCanvas.toDataURL('image/png');
$.ajax({
url: 'http://localhost:3000/upload-image',
dataType: 'json',
data: { data: dataURL },
type: 'POST',
success: function(data) {}
});
Receiving request:
router.post('/', (req, res) => {
const base64 = req.body.data.replace(/^data:image\/png;base64,/, "");
fs.writeFileSync(`uploads/images/newImage.jpg`, base64, {encoding: 'base64'});
}
So I did it this way:
var request = new XMLHttpRequest();
request.open("POST", "/test");
var fd = new FormData();
fd.append("file", avatarInput.files[0]);
request.send(fd);
I created a FormData Object, appended the image, which the user chose in an input called "avatarInput", and send the object to the server.
On server side I used express-fileupload to access the file:
app.post("/test", (req, res) => {
if(req.files){
//With the follwing command you can save the recieved image
req.files.file.mv("./file.png", (err) => {if(err)throw err});
}
res.end();
});
I need upload image with AngularJS without form. but I don't know how to receive it in Laravel, send it.
My code is this:
<input type="file" name="file" accept="image/jpeg, image/png" id="file" ng-model="data.image">
$('input[type=file]').change(function () {
$scope.img = this.files[0];
var filePath = $("#file").val();
var reader = new FileReader();
reader.onload = function (e) {
$('#image').attr('src',e.target.result);
$scope.img["imgbase64"] = e.target.result;
};
reader.readAsDataURL(this.files[0]);
});
I use the service here:
var imgSend = new FormData();
imgSend.append("file",$scope.img);
data["image"] = imgSend;
url = "maquinas"; registroMaquinaServices.servicesRegistroMaquinaPost(url,data).then(function(promise){
var requests = promise.data.response;
console.log(requests);
})
I'm sending this to laravel.
Thanks.
You can use https://github.com/ghostbar/angular-file-model
to handle your image file for uploading and then you will be able to create form object and send it to your laravel server to be able to get the image file as regular uploaded file, not a base64 encoded one.
this is the code i use to do so
in the example all of the data that needs to be sent to server is in $scope.data variable
$http({
headers: {
'Content-Type': undefined //undefined value is on purpose
},
method: method,
url: url,
data: $scope.data,
transformRequest: function(data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function(value, key) {
formData.append(key, value);
});
return formData;
}
})
I'm developing a set of tools in JavaScript and I'm having a trouble with saving static images. First of all I've created uploader to upload images that are later saved in upload/ directory.
Uploaded images (file) are sent to server like this:
$.ajax({
data: { file: e.dataTransfer.file },
url: 'server/uploading_files.php',
method: 'POST',
success: function (response) {
....
}
});
And I would love to do the same with images where I have only path to them -> statically save them.
Problem is in structure I'm sending to server side. Because e.dataTransfer.file looks like this:
FileList{0: File, length: 1}
0: File
lastModified:1441797733000
lastModifiedDate:Wed Sep 09 2015 13:22:13 GMT+0200 (CEST)
name:"sp_dom1.jpg"
size:563989
type:"image/jpeg"
webkitRelativePath:""
And when I want to save static image I have only path without any structure.
Is there any solution how to crate the same structure for uploading static images? I don't want to use 2 different .php files for save.
You can utilize XMLHttpRequest, with responseType set to "blob", new File() constructor available at chrome / chromium 38+
var dfd = new $.Deferred();
var pathToImage = "http://lorempixel.com/50/50/";
var request = new XMLHttpRequest();
request.responseType = "blob";
request.open("GET", pathToImage);
request.onload = function() {
var file = this.response;
dfd.resolve(
new File([file]
, file.name
|| "img-" + new Date().getTime()
+ "." + file.type.split("/")[1]
, {
type: file.type
}
)
)
};
request.send();
dfd.then(function(data) {
// do stuff with `data`
// i.e.g.;
// $.ajax({
// data: { file: data },
// url: 'server/uploading_files.php',
// method: 'POST',
// success: function (response) {
// ....
// }
// });
console.log(data);
var img = new Image;
img.onload = function() {
$("body").append(this)
}
img.src = URL.createObjectURL(data);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
I am trying to :
Send a zip file via xmlhttp to the client
then read the file using zip.js and render its contents
I successfully receive the binary of the file i.e. the success callback is called but I get and error when I try to do getEntries. I think the error is with the way of sending stream , please help.
Error msg :
Error in reading zip file
My client side code (using angular) :
$http.get(window.location.origin + '/book/'+bookName,{responseType:"Blob"}).
success(function (data , error) {
var a = new Uint8Array(data);
//var dataView = new DataView(data);
//var blob = new Blob(dataView.buffer);
zip.useWebWorkers = true;
zip.workerScriptsPath = '/js/app/';
zip.createReader(new zip.BlobReader(data), function(reader) {
// get all entries from the zip
reader.getEntries(function(entries) { //HERE I GET THE ERROR
if (entries.length) {
// get first entry content as text
entries[0].getData(new zip.TextWriter(), function(text) {
// text contains the entry data as a String
console.log(text);
// close the zip reader
reader.close(function() {
// onclose callback
var a = 0;
});
}, function(current, total) {
// onprogress callback
var a = 0;
});
}
});
},
function(error) {
// onerror callback
var a = 0;
});
})
.error( function (data , error) {
var a = 0;
});
My Server side code on Node:
router.get('/book/:bookName',function (req , res ) {
console.log('Inside book reading block : ' + req.params.bookName);
req.params.bookName += '.zip';
var filePath = path.join(__dirname,'/../\\public\\books\\' ,req.params.bookName );
var stat = fileSystem.statSync(filePath);
res.writeHead(200, {
//'Content-Type': 'application/zip',
'Content-Type': 'blob',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// replace all the event handlers with a simple call to readStream.pipe()
readStream.pipe(res);
});
It is probable that you might have already found a solution. I faced the same problem today and this is how I solved it in plain javascript:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'assets/object/sample.zip', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
// response is unsigned 8 bit integer
var responseArray = new Uint8Array(this.response);
var blobData = new Blob([responseArray], {
type: 'application/zip'
});
zip.createReader(new zip.BlobReader(blobData), function(zipReader) {
zipReader.getEntries(displayEntries);
}, onerror);
};
xhr.send();
The problem I see in your code is that you are changing the value to Uint8Array and assigning it to var a, but still use the raw data in blobreader. Also the blob reader required blob and not an array. So you should have converted var a into blob and then used it for reading.