With the help of this link 'https://gist.github.com/nathanpc/2464060' I have written code to download a file in PhoneGap. I tried it on Android phone and it works perfectly.
But on Windows phone, It says that it has downloaded and the path is -- //xyz/SIFA.pdf.
To look at the file system on Windows phone I have downloaded an app called 'Files' using which I looked up on the phone but I could not find any folder xyz nor the file.
I also connected the Windows phone to my PC and had a look but could not find the folder nor the pdf
Could you suggest what I am doing wrong in the code or if I am not looking for the file in the right way.
Thanks for your help in advance
Here is my code to download file in PhoneGap.
I have added alerts to indicate the progress.
var folderName = 'xyz';
var fileName;
var downloadFileOne = function (URL) {
//step to request a file system
alert("step one");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
alert("step two");
function fileSystemSuccess(fileSystem) {
alert("step three");
var download_link = encodeURI(URL);
alert("step four - " + download_link);
fileName = download_link.substr(download_link.lastIndexOf('/') + 1); //Get filename of URL
var directoryEntry = fileSystem.root; // to get root path of directory
directoryEntry.getDirectory(folderName, {
create: true,
exclusive: false
}, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
alert("step five");
var rootdir = fileSystem.root;
var fp = fileSystem.root.toNativeURL(); // Returns Fullpath of local directory
fp = fp + "/" + folderName + "/" + fileName; // fullpath and name of the file which we want to give
// download function call
filetransfer(download_link, fp);
}
function onDirectorySuccess(parent) {
// Directory created successfuly
alert("directory created successfully");
}
function onDirectoryFail(error) {
//Error while creating directory
alert("Unable to create new directory: " + error.code);
}
function fileSystemFail(evt) {
//Unable to access file system
alert(evt.target.error.code);
}
}
function filetransfer(download_link, fp) {
alert("step six - file transfer method");
var fileTransfer = new FileTransfer();
// File download function with URL and local path
fileTransfer.download(download_link, fp,
function (entry) {
alert("download complete: " + entry.fullPath);
},
function (error) {
//Download abort errors or download failed errors
alert("download error source " + error.source);
}
);
}
Related
In my NativeScript-Vue app, I make a POST request to my server and receive a binary file. It's a .zip file containing a .db file which I want to copy and initialize with the nativescript-sqlite plugin.
I am using axios and the POST response looks like this:
"PK {[oP'g�R 606.db�}`�����ו�N�-{�*�*�O炵W$�滓\(��t�KZ��dc2�e�C�Ĕ$�L
>b!��... and so on
Right now I am testing on Android. I am saving the file to the Android Downloads folder to see if I can unzip it. I know that File.write accepts a native byte array, so I am trying to get one from the binary file string.
import * as fs from "tns-core-modules/file-system";
async function saveToFile(binary) { // binary = "PK {[oP'g�R...
let folder = fs.Folder.fromPath(android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
let zipFile = folder.getFile("Database.zip");
// string to buffer
let buffer = new ArrayBuffer(binary.length);
let view = new Uint8Array(buffer);
for (let i = 0; i < view.length; i++) {
view[i] = binary.charCodeAt(i);
}
// buffer to native byte array
let array = Array.create("byte", view.byteLength);
for (let i = 0; i < view.byteLength; i++) {
array[i] = new java.lang.Byte(view[i]);
}
await zipFile.write(array);
}
I think I am doing things wrong, cycling arrays two times, anyway I am able to write the file but I can't open it as a .zip. Any help?
Solved switching from axios to NativeScript HTTP module, handling directly a File object instead of a string.
import { getFile } from "tns-core-modules/http";
import { Zip } from "nativescript-zip";
async function saveDatabaseToFile() {
let folder = fs.knownFolders.temp();
let zipFile = await getFile({
method: "POST", // url, headers, content
});
await file.rename("Database.zip"); // extension was messed up
await Zip.unzip({
archive: file.path,
directory: folder.path
});
let files = await folder.getEntities();
let dbFile = files.find(file => file._extension === ".db");
return dbFile;
}
I have this code for downloading a file which runs correct:
var base64EncodedBytes = System.Convert.FromBase64String(item.FileDataAsBase64String);
var downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadDirectory, "test.pdf");
var streamWriter = File.Create(filePath);
streamWriter.Close();
File.WriteAllBytes(filePath, base64EncodedBytes);
I'm able to locate the file I downloaded in the Downloads folder, but also I want to show a notification in the notification bar that the file has been downloaded and with a click in the notifications the user to be able to open the downloaded file.
Is that possible?
You can use Plugin.LocalNotification to show the notification once the file is downloaded.
try
{
var base64EncodedBytes = System.Convert.FromBase64String(item.FileDataAsBase64String);
var downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadDirectory, "test.pdf");
var streamWriter = File.Create(filePath);
streamWriter.Close();
File.WriteAllBytes(filePath, base64EncodedBytes);
DisplayNotification("test.pdf downloaded successfully", filePath);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.ToString());
DisplayNotification("Download Failed",string.Empty);
}
public void DisplayNotification(string message, string filePath)
{
var notification = new NotificationRequest
{
NotificationId = 100,
Title = "Your App name",
Description = message,
ReturningData = filePath, // Returning data when tapped on notification.
NotifyTime = DateTime.Now.AddSeconds(30) // Used for Scheduling local notification, if not specified notification will show immediately.
};
NotificationCenter.Current.Show(notification);
}
Note: Make sure to initialize the plugin setup in both the project iOS and Android.
I have searched and tried so many tutorials but i haven't got any working code for listing internal/external storage files absolute path.
I do have code for access only one file from internal storage -
var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "test.mp3");
Thanks in advance
This code gets the external storage path. It return the emulated copy if there is no actual removable device.
var _path = GetExternalFilesDirs(null);
string Datapath;
foreach (var spath in _path)
{
if (spath == null) //just loop on if there is no card inserted
continue;
if (Android.OS.Environment.InvokeIsExternalStorageEmulated(spath))
{ //Emulated
Datapath = spath.AbsolutePath.ToString();
}
else if (Android.OS.Environment.InvokeIsExternalStorageRemovable(spath))
{ //removable
Datapath = spath.AbsolutePath.ToString();
break;
}
}
I am using the S3 adaptor to save images to my S3 bucket. My client code is:
var saveFileToParse = function(imageData) {
var parseFile = new Parse.File(Parse.User.current().id + " Image", {
base64: imageData
});
$ionicLoading.show();
parseFile.save().then(function(response) {
if (angular.isNumber($scope.activeExercise.images[0])) {
$scope.activeExercise.images = [];
}
var imageUrl = response._url;
$scope.activeExercise.images.push(imageUrl);
$scope.$apply();
$scope.customImage = true;
$ionicLoading.hide();
}).then(function(imageUrl) {
var file = new Parse.Object("Files");
file.set("file", parseFile);
file.save().then(function(response) {
$ionicLoading.hide();
});
},
function(error) {
$ionicLoading.hide();
errorFactory.checkError(error);
});
};
The file is being saved, however is being saved as a .txt file, I expect because of the base 64, however this was never an issue on parse.com. Can I explicitly make this save as .jpg?
EDIT:
I am employed the code below and this gives a different filename and shows as an image in S3. However, when downloaded it still has a .txt file extension. I have even changed my save command to include the mime-type var parseFile = new Parse.File(name, file, "image/jpeg");
The issue here was caused by the old parse.com server automatically applying %20 when there was a space in the file URL.
Removing the space made it work.
Honestly, you just need to read the documentation thoroughly. The answer is already available there, so just pass the file object.
var fileUploadControl = $("#profilePhotoFileUpload")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.jpg";
var parseFile = new Parse.File(name, file);
parseFile.save().then(function () {
// The file has been saved to Parse.
}, function (error) {
// The file either could not be read, or could not be saved to Parse.
});
}
This script is attempting to:
create a new folder
scan an InDesign document for all images
convert all images to grayscale in Photoshop
save new grayscale images in the new folder from Photoshop
Converting the images to grayscale in Photoshop requires the use of the BridgeTalk object, which allows for the communication between InDesign and Photoshop (the usage of the BridgeTalk object seems to be a form of Ajax).
What I have so far is almost working, being that a new folder is created, and InDesign does seem to be communicating with Photoshop via BridgeTalk. But when Photoshop is opened, nothing happens -- no new images are saved, and I'm not sure if the grayscale conversion is taking place or not...
Here is my code:
#target "InDesign"
var inDesignDocument = app.activeDocument;
var newFolder = createFolder(inDesignDocument); // if subdirectory images DNE, create this folder with the function below
sendImagesToPhotoshop(inDesignDocument, newFolder);
//---------------------------------------------------------------------------------------------------------------
function createFolder(doc)
{
try
{
/*
* type-casting the filePath property (of type object) into a String type;
* must be a String type to concatenate with the subdirectory variable (also of type String)
*/
var docPath = String(doc.filePath);
var subdirectory = "/BLACK AND WHITE IMAGES";
}
catch(e)
{
alert(e.message);
exit();
}
var imagesFolder = docPath + subdirectory; // concatenating the two variables
if(!Folder(imagesFolder).exists)
{
Folder(imagesFolder).create();
}
return imagesFolder; // for instantiation outside of this function
} // end of function createFolder
//---------------------------------------------------------------------------------------------------------------
function sendImagesToPhotoshop(doc, folder)
{
var imgs = doc.allGraphics;
var fileName = "";
var img = "";
var imgType = "";
for(var i = 0; i < imgs.length; i++)
{
if(imgs[i].itemLink != null)
{
fileName = imgs[i].itemLink.name;
img = new File(folder + "/" + fileName); // each image instantiated here
imgType = imgs[i].imageTypeName; // image type is determined here (.tif, .jpg, .png, etc..)
alert("The file \"" + fileName + "\"\n\tis a " + imgType + " file.");
// each image exported to the new folder here, by file type
switch(imgType)
{
case "GIF":
alert("This script cannot convert and export the GIF file:\n\t" + fileName + " !");
break;
case "JPG":
case "EPS":
case "PNG":
case "TIFF":
createBridgeTalkMessage(folder);
break;
default:
alert("\tUnlisted image type: " + imgType + "!\nAdd this type to the switch statement.");
break;
} // end of switch statement
} // end of if statement
} // end of for loop
} // end of function sendImagesToPhotoshop
//---------------------------------------------------------------------------------------------------------------
function createBridgeTalkMessage(imagesFolder)
{
var bt = new BridgeTalk();
bt.target = "photoshop";
bt.body = saveNewImageInPhotoshop.toSource() + "(" + imagesFolder.toSource() + ");";
bt.onError = function(e)
{
alert("Error: " + e.body);
}
bt.onResult = function(resObj){};
bt.send();
}// end of function createBridgeTalkMessage
//---------------------------------------------------------------------------------------------------------------
// called from function createBridgeTalkMessage
function saveNewImageInPhotoshop(imagePath)
{
var photoshopDoc = "";
app.displayDialogs = DialogModes.NO; // Photoshop statement, prevents status alerts from interrupting
photoshopDoc.changeMode(ChangeMode.GRAYSCALE); // convert image to GRAYSCALE
photoshopDoc.saveAs(new File(imagePath) );
photoshopDoc.close(SaveOptions.DONOTSAVECHANGES);
} // end of function saveNewImageInPhotoshop
This is based on the work of Kasyan Servetsky, found here: http://forums.adobe.com/message/3817782
Yeah I experienced issues recently with single line comments and indeed using /* ... */ did the trick. I think you can pass a string for your url but need to escape the slashes characters.
It seems you are passing a folder to Photoshop instead of an actual image file. That may probably explain your issue ;)
Loic