i am trying to upload image captured from camera using ionic and capacitor and below code i am using:
var url = 'https://api.cloudinary.com/v1_1/' + this.cloudName + '/image/upload';
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open('POST', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader("Access-Control-Allow-Origin","*")
xhr.onreadystatechange = (e) => {
this.loading = false;
if (xhr.readyState == 4 && xhr.status == 200) {
// File uploaded successfully
var response = JSON.parse(xhr.responseText);
var url = response.secure_url;
// Create a thumbnail of the uploaded image, with 150px width
var tokens = url.split('/');
tokens.splice(-2, 0, 'w_150,c_scale');
var img = new Image(); // HTML5 Constructor
img.src = tokens.join('/');
img.alt = response.public_id;
document.body.appendChild(img);
//window.alert(url);
this.imageUrl = url;
this.capturedImage = this.base64Image;
//alert('capture:' + capturedImage);
}else{
console.log("unable to load image to the cloud" + xhr.readyState + ":" + xhr.status + ":" + xhr.responseText)
}
};
fd.append('upload_preset', this.unsignedUploadPreset);
fd.append('tags', emailid); // Optional - add tag for image admin in Cloudinary
fd.append('file', this.base64Image);
xhr.send(fd);
it prints: unable to load image to the cloud 4:0:
I'm a little confused by your code because it looks like you are trying to access the response before you've actually sent anything. I would recommend using one of the Cloudinary SDKs as it will make your life a lot easier.
https://cloudinary.com/documentation/image_upload_api_reference#upload_examples
Here is an example of another upload using Ionic and Capacitor.
https://devdactic.com/ionic-image-upload-capacitor
Related
I'm trying to open a PDF file with print dialog in IE Edge, it works fine in chrome but not in IE
MVC code to return file using Evo Pdf tool:
var restClient = new RestClient(Request.Url.Scheme + "://" + Request.Url.Authority);
var restResponse = restClient.Execute(request);
if (restResponse.StatusCode == HttpStatusCode.OK)
{
htmlModel.HtmlString = restResponse.Content;
byte[] pdfBytes = PdfUtil.GetEvoPdfBytes(htmlModel);
if (pdfBytes != null)
{
return File(pdfBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, htmlModel.PdfName + ".pdf");
}
}
Javascript code to open file with print dialog, below code works in chrome but not IE:
var req = new XMLHttpRequest();
req.open("POST", "/api/HtmlToPdf", true);
req.setRequestHeader("Content-Type", "application/json");
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var lin = window.URL.createObjectURL(blob);
// Works in chrome
var mywindow = window.open(lin, "_blank");
mywindow.focus();
mywindow.print();
};
req.send(JSON.stringify(
{
htmlModel: {
ElementSelector: "#div",
PageOrientation: "Portrait",
PdfName: "abc"
}
}));
IE11 does not support URL.createObjectURL(). So your code will not work for IE browser and you will not be able to open the blob with print dialog..
As a work around, you need to use msSaveBlob or msSaveOrOpenBlob for Internet Explorer browser.
These methods allow a user to save the file on the client as if the file had been downloaded from the Internet.
var blobObject = new Blob(["This is sample text..."]);
window.navigator.msSaveOrOpenBlob (blobObject, 'msSaveOrOpenBlob_testFile.txt');
References:
(1) Download a blob from HTTP URL in IE 11
(2) Saving files locally using Blob and msSaveBlob
(3) Blob download is not working in IE
I made an IOS 9 app using Phonegap 6.2.0. I need to play videos with no connection, so I download it using cordova FileTransfer plugin:
var uri = encodeURI(file.url);
var fileTransfer = new FileTransfer();
// var fileLocation = cordova.file.applicationStorageDirectory +
// '/Documents/' + file.folder + '/' + file.fileName;
var fileLocation = cordova.file.dataDirectory + file.fileName;
var deferred = $q.defer();
fileTransfer.headers = {
Connection: "close"
};
fileTransfer.download(uri, fileLocation, function(result) {
console.log("Fichero descargado: " + JSON.stringify(result));
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
I've tried different file locations to download it (https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/)
Then, I return the file path using resolveLocalFileSystemURL:
var deferred = $q.defer();
var nativePath = cordova.file.dataDirectory + nombreFichero + "." + extension;
resolveLocalFileSystemURL(nativePath, function(entry) {
//deferred.resolve(entry.nativeURL);
console.log("Fichero native: " + entry.toNativeURL());
console.log("Fichero fullPath: " + entry.fullPath);
console.log("Fichero toUrl: " + entry.toURL());
console.log("Fichero toInternalURL: " + entry.toInternalURL());
deferred.resolve(entry.toURL());
}, function(error) {
console.log("Error al leer el fichero: " + JSON.stringify(error));
deferred.reject(error);
});
return deferred.promise;
I've tried all file formats but none of them worked:
cdvfile://localhost/library-nosync/97a7d50f-05d1-4642-96e9-b0b26ea41897.mp4
file:///var/mobile/Containers/Data/Application/6CD24D7A-7A39-4AFE-A43B-788FCDFCEB5A/Library/NoCloud/a88d38b8-85e8-4b9b-b57e-a8eb2731eb0d.mp4
http://localhost/library-nosync/97a7d50f-05d1-4642-96e9-b0b26ea41897.mp4 and using port 12344
Some formats do nothing, some show the button play strikethrough...
In all answers I had read they recommend to use .toNativeUrl() but it doesn't work for me...
I also tried cordova-plugin-streaming-media (I can't post more links), but it does not work (no play video, no errors...)
Any idea?
Solved.
My code works good and play videos. The problem was in the URL to download the video, it gets a string with the url and not the video (therefore download and open file method didin't throw error)
Summarizing, toUrl() works.
Thanks #Gandhi for your replies.
I have an app built in Ionic Framework, and the backend of this app has a Rails app administrator panel, with content editor, user control, image uploads (using Carrierwave).
I made a API that returns the concise information to Ionic app. And isolates the Rails admin panel in a private network.
I get fully posts contents, relations from the another objects, and sends to Ionic app via JSON.
But I don't how properly deals with uploaded (via Carrierwave) assets to show the images in my Ionic app.
Thanks,
then first you have to add 3 plugins which are below
cordova plugin add org.apache.cordova.file-transfer
cordova plugin add org.apache.cordova.file
cordova plugin add org.apache.cordova.camera
And copy below code and pest into your controller to pick image from
gallery and upload on server
$scope.editProfileImgGallary = function() {
navigator.camera.getPicture(uploadEditProfilePhotosImage, onFailEditProfilePhoto, {
targetWidth: 512,
targetHeight: 512,
quality: 40,
correctOrientation: true,
allowEdit: true,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});
}
function onFailEditProfilePhoto(message) {
// alert('Failed because: ' + message);
}
function uploadEditProfilePhotosImage(imageURI) {
// $ionicLoading.show({
// template: '<p>Loading...</p><ion-spinner icon="bubbles"></ion-spinner>'
// });
console.log(imageURI);
// var img = document.getElementById('userEditProfileImg');
// img.src = imageURI;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI('uploadimg.php'), winEditProfilePhotos, failEditProfilePhotos, options);
}
function winEditProfilePhotos(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// $ionicLoading.hide();
}
function failEditProfilePhotos(error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
// $ionicLoading.hide();
// var alertPopup = $ionicPopup.alert({
// title: 'Uh Oh!',
// template: 'You Get Some Error Please Try Again..'
// });
}
And copy bellow code and pest into your HTML page onClick Event
<div ng-click="editProfileImgGallary();" ></div>
The scenario goes like this: I open a website in InAppBrowser, after the user ends with the work over there, the site generates a .pdf for the user to download, the problem is that the pdf does not download, it opens it in the browser.
Is there a way to make it download from the InAppBrowser? I'm currently working on an iOS app, so the solution would be better for iOS.
Thanks in advance.
Following #jcesarmobile advices this is what I came up with:
First I had to install the cordova-plugin-file-transfer
Open URL
var url = "http://mi-fancy-url.com";
var windowref = window.open(url, '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
Create a listener on that windowref for a loadstart event and check if what's being loaded is a pdf (that's my case).
windowref.addEventListener('loadstart', function(e) {
var url = e.url;
var extension = url.substr(url.length - 4);
if (extension == '.pdf') {
var targetPath = cordova.file.documentsDirectory + "receipt.pdf";
var options = {};
var args = {
url: url,
targetPath: targetPath,
options: options
};
windowref.close(); // close window or you get exception
document.addEventListener('deviceready', function () {
setTimeout(function() {
downloadReceipt(args); // call the function which will download the file 1s after the window is closed, just in case..
}, 1000);
});
}
});
Create the function that will handle the file download and then open it:
function downloadReceipt(args) {
var fileTransfer = new FileTransfer();
var uri = encodeURI(args.url);
fileTransfer.download(
uri, // file's uri
args.targetPath, // where will be saved
function(entry) {
console.log("download complete: " + entry.toURL());
window.open(entry.toURL(), '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
true,
args.options
);
}
The problem i'm facing now is the path where it downloads, I just can't open it. But well, at least file is now downloaded. I will have to create a localStorage item to save the paths for different files.
Many validations are missing in this steps, this was just an example I made quickly to check if it works. Further validations are needed.
Open you window using IAB plugin and add an event listener
ref = window.open(url, "_blank");
ref.addEventListener('loadstop', loadStopCallBack);
In the InAppBrowser window call the action using https://xxx.pdf">documentName
Implement the loadStopCallBack function
function loadStopCallBack(refTemp) {
if(refTemp.url.includes('downloadDoc')) {
rtaParam = getURLParams('downloadDoc', refTemp.url);
if(rtaParam != null)
downloadFileFromServer(rtaParam);
return;
}
}
function getURLParams( name, url ) {
try {
if (!url)
url = location.href;
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
return results == null ? null : results[1];
} catch (e) {
showSMS(e);
return null;
}
}
After create a download method
function downloadFileFromServer(fileServerURL){
try {
var Downloader = window.plugins.Downloader;
var fileName = fileServerURL.substring(fileServerURL.lastIndexOf("/") + 1);
var downloadSuccessCallback = function(result) {
console.log(result.path);
};
var downloadErrorCallback = function(error) {
// error: string
console.log(error);
};
//TODO cordova.file.documentsDirectory for iOS
var options = {
title: 'Descarga de '+ fileName, // Download Notification Title
url: fileServerURL, // File Url
path: fileName, // The File Name with extension
description: 'La descarga del archivo esta lista', // Download description Notification String
visible: true, // This download is visible and shows in the notifications while in progress and after completion.
folder: "Download" // Folder to save the downloaded file, if not exist it will be created
};
Downloader.download(options, downloadSuccessCallback, downloadErrorCallback);
} catch (e) {
console.log(e);
}
}
you can get the plugin here https://github.com/ogarzonm85/cordova-plugin-downloader
it Works and was too easy
I tried this, it works on android phone. In iOS, I could show 'The image has been downloaded' alert, but I couldn't find the image in iPhone image gallery.
var path = 'http://example.com';
if( navigator.connection.type == Connection.NONE ) {
navigator.notification.alert('unable to download an image due to disconnect network.');
return;
} else {
var uri = encodeURI(path);
var fileName = path.split('/').pop();
var filePath = fileSystem.root.toURL() + fileName;
var fileTransfer = new FileTransfer();
fileTransfer.download(uri, filePath, function(entry){
navigator.notification.alert( 'The Image has been downloaded.')
});
}