How to create and upload a video to parse server? - javascript

I am able to upload image file to S3 using parse server. (by creating parse file from base64 image data and doing save() on parse file)
How can I do the same thing for a video file? I am doing this using parse-server js library in Ionic 2 app with typescript. The below code worked for images.
let file = new Parse.File("thumbnail", { base64: imageData });
file.save().then(() => {
// The file has been saved to Parse.
console.log("File uploaded....");
}, (error) => {
// The file either could not be read, or could not be saved to Parse.
console.log("File upload failed.");
});
In case of a video file, I have the file location received from cordova media capture callback. Help me in uploading the video file.
Thank you

here is my solution after days of research.
it works for iphone.
the important statement is this:
data=data.replace("quicktime","mov");
var options = { limit: 1, duration: 30 };
navigator.device.capture.captureVideo(function(files){
// Success! Audio data is here
console.log("video file ready");
var vFile = files[0];
console.log(vFile.fullPath);
///private/var/mobile/Containers/Data/Application/7A0069EB-F864-438F-A685-A0DAE97F8B2D/tmp/capture-T0x144510b50.tmp.GfXOow/capturedvideo.MOV
self.auctionvideo = vFile.fullPath; //localURL;
console.log(self.auctionvideo);
var fileReader = new FileReader();
var file;
fileReader.onload = function (readerEvt) {
var data = fileReader.result;
data=data.replace("quicktime","mov");
console.log(data);
//data:video/quicktime;base64,AAAAFGZ0
console.log(data.length);
self.auctionvideo=data;
self.videofile = {base64:data};
};
//fileReader.reasAsDataURL(audioFile); //This will result in your problem.
file = new window.File(vFile.name, vFile.localURL,
vFile.type, vFile.lastModifiedDate, vFile.size);
fileReader.readAsDataURL(file); //This will result in the solution.
// fileReader.readAsBinaryString(file); //This will result in the solution.
},
function(error){
},
options);

Related

Convert buffer to file [FileCollection:meteor/ostrio:files]

when i get the image from the input
i have to convert it to a buffer to make some operations with the image, so as a result a i have a buffer instead of file.
im using FileCollection in meteor to store the image in mongo collection
uploadIt(e) {
e.preventDefault();
var reader = new FileReader();
var buffer;
var file = e.currentTarget.files[0];
if (e.currentTarget.files && e.currentTarget.files[0]) {
reader.onload = function(e){
buffer = new Uint8Array(reader.result);
// some operations over the buffer
};
reader.readAsArrayBuffer(file);
if (file) {
let uploadInstance = CourseFilesCollection.insert({
file: buffer,
..
..
})
}
}
but when i insert it got this error
message: "[FilesCollection] [insert] Have you forget to pass a File itself?
the code originally was
if (file) {
let uploadInstance = CourseFilesCollection.insert({
file: file,
..
..
})
}
but since i had to perfom operations over the the image i need to someway conver the buffer to file
any ideas how to solve this ?
Short answer
use the file constructor to turn bits back to a file container:
file: new File([buffer], file.name, file)
you could try using blob also with wider browser support... but if you want to use the latest tech, then:
async uploadIt (evt) {
evt.preventDefault()
const file = evt.currentTarget.files[0]
if (!file) return
const buffer = new Uint8Array(await file.arrayBuffer())
// some operations over the buffer
const uploadInstance = CourseFilesCollection.insert({
file: new File([buffer], file.name, file)
})
}

How do I send image to server via socket.io?

I've been beating my head over this and I can't find a proper solution.
I want to be able to upload images to the server via socket.io emit and save them to a MongoDB database later. How do I do this? I've seen people doing it with base64 encoding but I can't figure out how that exactly works, there are other questions on this website asking about sending an image to client from server via socket.io but none about this. All help is appreciated. <3
Goal: To upload an image to server with socket.emit('image', someimagefile) or similar.
I'd really appreciate if you provide a similar way to send an image to the client.
As you mentioned, you can convert the image to base64 using FileReader.readAsDataURL and send the encoded string, and decode it on the server:
document.getElementById('file').addEventListener('change', function() {
const reader = new FileReader();
reader.onload = function() {
const base64 = this.result.replace(/.*base64,/, '');
socket.emit('image', base64);
};
reader.readAsDataURL(this.files[0]);
}, false);
socket.on('image', async image => {
const buffer = Buffer.from(image, 'base64');
await fs.writeFile('/tmp/image', buffer).catch(console.error); // fs.promises
});
Or better use FileReader.readAsArrayBuffer to get an array of bytes that you'll send to the server.
document.getElementById('file').addEventListener('change', function() {
const reader = new FileReader();
reader.onload = function() {
const bytes = new Uint8Array(this.result);
socket.emit('image', bytes);
};
reader.readAsArrayBuffer(this.files[0]);
}, false);
socket.on('image', async image => {
// image is an array of bytes
const buffer = Buffer.from(image);
await fs.writeFile('/tmp/image', buffer).catch(console.error); // fs.promises
});
To receive from the server:
// Server side
socket.emit('image', image.toString('base64')); // image should be a buffer
// Client side
socket.on('image', image => {
// create image with
const img = new Image();
// change image type to whatever you use, or detect it in the backend
// and send it if you support multiple extensions
img.src = `data:image/jpg;base64,${image}`;
// Insert it into the DOM
});
Base64 can work, but one more thing to keep in mind is that socket buffer size limit is 1 MB. (This can be increased according to docs).
So I guess if the file size is huge, its better to stream it with something like socket.io-stream
i don't know if any one is looking for it anymore but I made possible to send media via socket.io... here is the code:
// sending media from client side
$("#send_media").change(function (e) {
var data = e.originalEvent.target.files[0];
var reader = new FileReader();
reader.onload = function (evt) {
var msg = {};
msg.file = evt.target.result;
msg.fileName = data.name;
socket.emit("base64 file", msg);
console.log(msg)
};
reader.readAsDataURL(data);
});
// showing media to ui
socket.on("base64 image", (msg) => {
console.log("as", msg);
$(".messages")
.append(`<img src=${msg.file} alt="Red dot" />`);
scrollToBottom();
});
// sending media from server side
socket.on("base64 file", function (msg) {
console.log("received base64 file from server: " + msg.fileName);
socket.username = msg.username;
io.to(roomId).emit('base64 image', //exclude sender
// io.sockets.emit(
// "base64 file", //include sender
{
file: msg.file,
fileName: msg.fileName,
}
);
});

Upload a photo to Firebase Storage with Image URI

I am currently attempting to upload a photo to my Firebase app's storage in my Apache Cordova app. I currently get the photo's URI with the following code:
function getPhotoFromAlbum() {
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM,
destinationType: navigator.camera.DestinationType.FILE_URI
});
}
function onPhotoURISuccess(imageURI) {
var image = document.getElementById('image');
image.style.display = 'block';
image.src = imageURI;
getFileEntry(imageURI);
}
And then am attempting to convert the image into a file and push it to my Firebase storage with the following function:
function getFileEntry(imgUri) {
window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {
console.log("got file: " + fileEntry.fullPath);
var filename = "test.jpg";
var storageRef = firebase.storage().ref('/images/' + filename);
var uploadTask = storageRef.put(fileEntry);
}, function () {
// If don't get the FileEntry (which may happen when testing
// on some emulators), copy to a new FileEntry.
createNewFileEntry(imgUri);
});
}
I have both the file and the camera cordova plugins installed, the only errors I get when I attempt to do this is
Error in Success callbackId: File1733312835 : [object Object]
Which is just an error message from cordova.js
I also know I have my Firebase storage set up correctly because I have tested it through an emulator by adding a file input and successfully uploading whatever file the user added, to the Firebase storage.
Is it possible to upload a file to Firebase storage using this method of converting an image to a file through its URI, and then uploading it? If so, what is the correct way to do so / what is wrong with the way i'm doing it?
I was able to accomplish uploading an image by using a data url. Below is my code:
var filename = "test.jpg";
var storageRef = firebase.storage().ref('/images/' + filename);
var message = 'data:image/jpg;base64,' + imageUri;
storageRef.putString(message, 'data_url').then(function (snapshot) {
console.log('Uploaded a data_url string!');
});
Is it possible to upload a file to Firebase storage using this method of converting an image to a file through its URI, and then uploading it? If so, what is the correct way to do so / what is wrong with the way i'm doing it?
Yes it is possible to upload a file on firebase through its URI. However you have to follow the correct way.
1. You have to store the data in firebase after file reading operation is completed.you can use FileReader.onloadend for this.
2. By using a data_url you can store to firebase.
Here is the snippet for more clarity:
function getFileEntry(imgUri) {
window.resolveLocalFileSystemURL(imgUri, function onSuccess(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function() {
filename = "test.jpg";
var storageRef = firebase.storage().ref('/images/' + filename);
var data = 'data:image/jpg;base64,' + imgUri;
storageRef.putString(data, 'data_url').then(function (snapshot) {
console.log('Image is uploaded by base64 format...');
});
};
reader.readAsArrayBuffer(file);
});
},
function onError(err) {
console.log(err);
createNewFileEntry(imgUri);
});
}

How to encode base 64 to .kml file?

I convert kml file to base 64. Now I want to encode base 64 to become kml file again? is this possible? I convert kml file like this..
$scope.myFunction = function () {
var files = document.getElementById('myFile').files;
if (files.length > 0) {
getBase64(files[0]);
}
}
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
how can I store kml file to database?
It surely is possible, you just have to decode the base64 and turn the result into a file again.
function base64ToFile(base64){
content=atob(base64);
var file = new Blob([content], {type: 'kml'});
//You can now asign the file to a link to download, send it with ajax, etc..
a.href = URL.createObjectURL(file);
}
Bear in mind, that you cant write a file directly onto disk from javascript, because that would be a security issue, you need t

Get base64 of audio data from Cordova Capture

I am using ngCordova Capture to write this code by recording audio and send the base64 somewhere (via REST). I could get the Capture Audio to work but once it returns the audioURI, I cannot get the data from the filesystem as base64. My code is below:
$cordovaCapture.captureAudio(options).then(function(audioURI) {
$scope.post.tracId = $scope.tracId;
$scope.post.type = 'audio';
console.log('audioURI:');
console.log(audioURI);
var path = audioURI[0].localURL;
console.log('path:');
console.log(path);
window.resolveLocalFileSystemURL(path, function(fileObj) {
var reader = new FileReader();
console.log('fileObj:');
console.log(fileObj);
reader.onloadend = function (event) {
console.log('reader.result:');
console.log(reader.result);
console.log('event.result:');
console.log(event.result);
}
reader.onload = function(event2) {
console.log('event2.result:');
console.log(event2.target.result);
};
reader.readAsDataURL(fileObj);
console.log(fileObj.filesystem.root.nativeURL + ' ' + fileObj.name);
$cordovaFile.readAsDataURL(fileObj.filesystem.root.nativeURL, fileObj.name)
.then(function (success) {
console.log('success:');
console.log(success);
}, function (error) {
// error
});
});
Here is the output in console log:
So how do I get the base64 data from the .wav file?
I have been reading these links:
PhoneGap FileReader/readAsDataURL Not Triggering Callbacks
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
http://jsfiddle.net/eliseosoto/JHQnk/
http://community.phonegap.com/nitobi/topics/filereader_onload_not_working_with_phonegap_build_2_5_0
Had same problem, which I fixed using both the Cordova Capture and Cordova File plugin.
navigator.device.capture.captureAudio(function (audioFiles) {
var audioFile = audioFiles[0],
fileReader = new FileReader(),
file;
fileReader.onload = function (readerEvt) {
var base64 = readerEvt.target.result;
};
//fileReader.reasAsDataURL(audioFile); //This will result in your problem.
file = new window.File(audioFile.name, audioFile.localURL,
audioFile.type, audioFile.lastModifiedDate, audioFile.size);
fileReader.readAsDataURL(file); //This will result in the solution.
});

Categories

Resources