Phonegap downloaded image on sdcard - javascript

I want to store an image on sdcard (android) with phonegap. But it is not working. I download the image with filetransfer.download. But it jumps in the error callback. The errocode that I get is 1. Here my Code:
window.resolveLocalFileSystemURI(cordova.file.externalRootDirectory + "/Pictures", function (fileSystem) {
var fileTransfer = new FileTransfer();
var uri = encodeURI("MyTopsecretPHPFunctionThatReturnsAnImage...");
var path = fileSystem.toURL() + "example.jpg";
alert(path);
fileTransfer.download(
uri,
path,
function(entry) {
alert("success!!" + path);
refreshMedia.refresh(path); // Refresh the image gallery
},
function(error) {
alert(error.source);
alert(error.target);
alert(error.code);
},
false,
{ headers: { "Authorization": "dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" }
});
},function(error) {
alert(error);
});
When I put it in cordova.file.externalDataDirectory it is working. Why can't I access to the pictures folder, or any other folder at the sdcard root directory?
And another question: where can I store the image on IOS? I want to show it on gallery...

I found a solution: I just added the Line:
fileSystem.getDirectory("Pictures", {create: true, exclusive: false});
Now I'm able to get the access rights on the sdcard.

Related

Webcam Recordings from in .mp4 or .webm are not play on MacOS Safari browser and on iOS devices

I record a video through VideoJS. The code looks like this:
// Video recording via webcam
var videoMaxLengthInSeconds = 180;
// Inialize the video player
let videoBlob;
var player = videojs("myVideo", {
controls: true,
width: 720,
height: 480,
fluid: false,
plugins: {
record: {
audio: true,
video: true,
maxLength: videoMaxLengthInSeconds,
debug: true,
videoMimeType: "video/mp4"
}
}
}, function() {
// print version information at startup
videojs.log(
'Using video.js', videojs.VERSION,
'with videojs-record', videojs.getPluginVersion('record'),
'and recordrtc', RecordRTC.version
);
});
// error handling for getUserMedia
player.on('deviceError', function() {
console.log('device error:', player.deviceErrorCode);
});
// Handle error events of the video player
player.on('error', function(error) {
console.log('error:', error);
});
// user clicked the record button and started recording !
player.on('startRecord', function() {
console.log('started recording! Do whatever you need to');
});
// user completed recording and stream is available
// Upload the Blob to your server or download it locally !
let recording;
let recordingData;
player.on('finishRecord', function() {
// the blob object contains the recorded data that
// can be downloaded by the user, stored on server etc.
recordingData = player.recordedData;
videoBlob = player.recordedData.video;
//let myblob = new Blob(player.recordedData, { type: "video/webm" });
let objectURL = window.URL.createObjectURL(player.recordedData)
let downloadButton = document.getElementById('downloadButton');
downloadButton.href = objectURL;
downloadButton.download = "Vlog.webm";
//recording = new File(myBlob, 'vlog.webm')
console.log(recording)
console.log('finished recording: ', videoBlob);
});
// Sending recorder video to server
$('#postButton').click(function() {
// Get form data
form = document.querySelectorAll('#form');
let formData = new FormData(form[0]);
let disabled = document.getElementById("commentsDisable").checked
console.log("Comments Enabled: " + disabled)
formData.append('commentsDisabled', disabled);
let selection = document.getElementById('categorySelect');
let selected = selection.options[selection.selectedIndex].value;
// Append selected category
formData.append('category', selected)
//Apend YouTube embed link
if (ytUrl) {
formData.append('ytlink', ytUrl)
}
// Append recordedBlob to form data as file
if (recordingData) {
console.log('Recording detected: ' + recordingData)
formData.append('videoFile', recordingData, recordingData.name);
}
//Append video from local upload
if (tempFile) {
formData.append('videoFile', tempFile);
}
// Send POST request via AJAX to server
$.ajax({
type: "POST",
url: "/make_vlog/",
processData: false,
contentType: false,
data: formData,
success: function(response) {
alert(response);
//location.href = "/vlogs";
}
});
});``
On the server side I have a django app which stores the file as .mp4 creates a new Vlog model.
When I open the page the video is loaded and can be played by all browsers. Except Safari and iOS devices don't play the video (Format not supported).
When I upload video from file instead of webcam recording. And the file is a valid mp4 video (for example from here:example_video) the file is played on every device and browser.
I think the problem is the video encoding in my js code. The same problem occurs with .webm file as well.
When I download the webm, convert into mp4 in VLC and upload on the server the video is played correctly.
Does anyone have experience with such problem?
Thanks
You need to convert the webm videos to mp4 server site for playback in Safari.
On web based webcam recording each browser saves in specific native format (mime type). Safari saves mp4/mp3 while other browsers usually save webm.
Changing the file extension does not help. You need to convert the video.
You can convert the webm to mp4 with ffmpeg, server side.

Upload image to cloudinary and to my own server using jquery file upload

I use jQuery File Upload to upload images to my server. Now I want to test out Cloudinary, but during testing I still want to upload all images to my own server as well.
The code I use for uploading images to my server is:
$(function () {
$('#fileupload').fileupload({
url: '/Upload/Upload.ashx',
maxFileSize: 15000000,
acceptFileTypes: /(\.|\/)(jpe?g)$/i,
dataType: "json",
autoUpload: true,
start: function (e) {
$('#progress').removeClass('hidden');
},
progress: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css('width', progress + '%');
},
always: function (e) {
$('#progress').addClass('hidden').fadeOut("slow");
},
done: function (e, data) {
$('#progress').addClass('hidden');
parent.location.reload();
},
})
.bind('fileuploadadd', function (e, data) {
$('#error').addClass('hidden');
})
.bind('fileuploadprocessfail', function (e, data) {
var currentFile = data.files[data.index];
if (data.files.error && currentFile.error) {
$('#error').html('error: ' + data.files[data.index].error);
$('#error').removeClass('hidden');
}
})
});
The code for uploading using Cloudinary is:
$('#fileupload').unsigned_cloudinary_upload('test12345',
{ cloud_name: 'test' }
).bind('cloudinarystart', function (e, data) {
$('#progress').show();
}
).bind('cloudinaryprogress', function (e, data) {
$('.progress-bar').css('width',
Math.round((data.loaded * 100.0) / data.total) + '%');
}
).bind('cloudinarydone', function (e, data) {
$('#progress').hide();
parent.location.reload();
});
Now I'm searching for a way to do both the same time or after each other.
What I tried?
I tried to putting the code from Cloudinary in the "done" part of the Jquery File Upload code but that is not working. I also tried to destroyed Fileupload first and then start the Cloudinary code, also not working. I tried to play with Jquery when/then, but still no succes. I searched Google and Stackoverflow but can not find anything that I need.
The first part of uploading (FileUpload) is working. But the Cloudinary part it not. No errors in the console window.
I need a way to combine the scripts.. can anybody help me out?
Update
I fixed it with only running the first script and in the Upload.ashx uploading to Cloudinay with asp.net. That is working.
public static UploadResult UploadImage(string tags, string fileName, Stream stream)
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(fileName, stream),
PublicId = fileName,
Tags = tags,
UploadPreset = "test12345",
};
var result = new Cloudinary(GetAccount()).Upload(uploadParams);
return new UploadResult
{
uri = result.SecureUri,
error = result.Error != null ? result.Error.Message : string.Empty
};
}
When you say "not working", you mean that the cloudinarydone event isn't fired at all after a successful upload? Because it should, and you should be able to get the details of it and to pass it to your server. Here's an example:
https://jsfiddle.net/taragano/70dd9vd4/
Alternatively, and it may be probably the more recommended approach, you can upload the image to your server first, and then do a server-side upload, i.e., have your server upload the image directly to your Cloudinary account.

Cordova File Plugin

I'm tearing my hair out trying to get the Cordova File Plugin and Cordova File Transfer to work, My code (below) should create a new folder 'Makes' and download an image into that new folder, but instead it just throws error code 1, but I can't figure out why, can someone please point me in the right direction:
function onAppReady(){
if(navigator.splashscreen && navigator.splashscreen.hide){
navigator.splashscreen.hide();
}
updateImages();
}
function updateImages(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
function fileSystemSuccess(fileSystem){
var directoryEntry=fileSystem.root;
directoryEntry.getDirectory("Makes", {create:true, exclusive:false}, onDirectorySuccess, onDirectoryFail);
}
function onDirectorySuccess(parent){
var rootdir = fileSystem.root;
var fp = parent.toURL();
var download_link=encodeURI('https://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/1122px-Wikipedia-logo-v2.svg.png');
var fpFull=fp+'Makes/Wikipedia.png';
filetransfer(download_link, fpFull);
}
function onDirectoryFail(error){alert("Unable to create new directory: "+error.code);}
function fileSystemFail(evt){alert(evt.target.error.code);}
}
function filetransfer(download_link, fp){
var fileTransfer=new FileTransfer();
fileTransfer.download(download_link, fp, function(entry){
console.log("download complete: "+entry.fullPath);
},
function(error){
console.log("download error: "+error.code+' - '+error.source+' - '+error.target);
});
}
document.addEventListener("app.Ready", onAppReady, false);

Using CollectionFS how can the url of a image be returned after upload?

I am trying to return the url of the uploaded image and make it equal to uploadedurl. This is all in a function that is triggered when a photo is dropped into the upload box. uploadedurl is currently being set to null and is returning this error The provided value 'undefined' is not a valid enum value of type XMLHttpRequestResponseType. in the client console. I am using amazon S3 to store the images That part works the images are stored in the S3 and do have usable urls under the domain. What did I do wrong?
var user = Meteor.user();
var uploadedurl;
Images.insert(newFile, function (error, fileObj) {
if (error) {
//do error
} else {
fileObj.once("uploaded", function () {
uploadedurl=fileObj.url();
document.getElementById("phototag").innerHTML = '<img src=&quot'+uploadedurl+'&quot >';
});
}
});
});
},
CollectionFS objects include a url() method. In your case use:
fileObj.url();
Note that it may take awhile for large files to finish uploading. fileObj.isUploaded() will be true when the upload is done. fileObj.url() will be null until that time.
In this github ticket #aldeed mentions attaching an event handler to the fileObj to be able to get a callback once the file uploads. This is better than polling with a setTimeout. In your case:
fileObj.once("uploaded", function () {
uploadedurl=fileObj.url();
});
try this..It worked for me
FS.Utility.eachFile(event, function(file) {
Images.insert(file, function(err, fileObj) {
if (err) {
console.log(err);
} else {
var cursor = Images.find(fileObj._id);
var liveQuery = cursor.observe({
changed: function(newImage, oldImage) {
if (newImage.isUploaded()) {
liveQuery.stop();
$("#image" + postId).attr("fileId", fileObj._id);
var fielname = fileObj.original.name;
setTimeout(function() {
var imageUrl = '/cfs/files/images/' + fileObj._id + '/' + fielname;
$("#imagefile" + postId).attr("src", imageUrl);
$("#imagediv" + postId).show();
}, 5000);
}
}
});
}
});});

Showing an image from LocalStore in HTML on PhoneGap/Cordovia on Windows Phone 7

What is required to show an image from LocalStorage in HTML markup on PhoneGap running on Windows Phone 7?
an image is downloaded from the Internet and stored on the phone (on Windows Phone 7 it can be stored only in LocalStorege of the application's domain);
this image is to be shown using PhoneGap \ Cordova HTML markup with <img> element;
using <img src="xyz"/> ain't working;
The solution was quite different from Android version.
Following steps are necessary:
load the image from localstore as binary data;
place it in the "src" attribute of the img element encoded;
Code:
var fileName = 'myappname/test.png';
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onFail);
function onFileSystemSuccess (fileSystem) {
fileSystem.root.getFile(fileName, null, gotFileEntry, onFail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(onGotFile, onFail);
}
function gotFile(onGotFile) {
var reader = new FileReader();
reader.onloadend = function (evt) {
$('#outerDiv').html('<img src="' + evt.target.result + '" />');
};
reader.readAsDataURL(file);
}
function onFail(evt) {
console.log('error: ' + evt.target.error.code);
}

Categories

Resources