I am trying to copy one jpg file from one folder into another in PhoneGap. The method I used is fs.download. However I got the error that the source url is unsupported. Here are the source and destination files.
source = "/var/mobile/Applications/9483756B-8D2A-42C5-8CF7-8D76AAA8FF2C/Shift.app/iqedata/5977e2e9239649d5a7e3b8a54719679f/06e2b8896e51472789fcc27575631f94.jpg";
target = "/var/mobile/Applications/9483756B-8D2A-42C5-8CF7-8D76AAA8FF2C/Documents/memoir/5977e2e9239649d5a7e3b8a54719679f.jpg";
Can anybody help me to implement the copyto method which I think should be the correct one to use to solve this problem? I only got the full path of both source and destination.
Thanks.
You want to use the copyTo method of the FileEntry object:
http://docs.phonegap.com/en/2.6.0/cordova_file_file.md.html#FileEntry
Using copyTo method wasn't always working for me, the moveTo method worked though.
The below code, copies a file from the www folder to the /Library/LocalDatabase folder:
function copyToLocation(dbName){
console.log("Copying :"+dbName);
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory+ "www/"+dbName,function (fileEntry)
{
window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory + "Library/LocalDatabase/",function (directory)
{
fileEntry.moveTo(directory, 'new_dbname.db',function(){
console.log('DB Loaded!');
},
function()
{
console.log('Unable to load DB');
});
//},null);
},null);
}, null);
}
Related
I am working on meanjs application generated using https://github.com/DaftMonk/generator-angular-fullstack. I am trying to generate a .pdf file using phantomjs and download it to the browser.
The issue is that the downloaded .pdf file always shows the blank pages regardless of the number of pages. The original file on server is not corrupt. When I investigated further, found that the downloaded file is always much larger than the original file on the disk. Also this issue happens only with .pdf files. Other file types are working fine.
I've tried several methods like res.redirect('http://localhost:9000/assets/exports/receipt.pdf');, res.download('client\\assets\\exports\\receipt.pdf'),
var fileSystem = require('fs');
var stat = fileSystem.statSync('client\\assets\\exports\\receipt.pdf');
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream('client\\assets\\exports\\receipt.pdf');
return readStream.pipe(res);
and even I've tried with https://github.com/expressjs/serve-static with no changes in the result.
I am new to nodejs. What is the best way to download a .pdf file to the browser?
Update:
I am running this on a Windows 8.1 64bit Computer
I had corruption when serving static pdfs too. I tried everything suggested above. Then I found this:
https://github.com/intesso/connect-livereload/issues/39
In essence the usually excellent connect-livereload (package ~0.4.0) was corrupting the pdf.
So just get it to ignore pdfs via:
app.use(require('connect-livereload')({ignore: ['.pdf']}));
now this works:
app.use('/pdf', express.static(path.join(config.root, 'content/files')));
...great relief.
Here is a clean way to serve a file from express, and uses an attachment header to make sure the file is downloaded :
var path = require('path');
var mime = require('mime');
app.get('/download', function(req, res){
//Here do whatever you need to get your file
var filename = path.basename(file);
var mimetype = mime.lookup(file);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
filestream.pipe(res);
});
There are a couple of ways to do this:
If the file is a static one like brochure, readme etc, then you can tell express that my folder has static files (and should be available directly) and keep the file there. This is done using static middleware:
app.use(express.static(pathtofile));
Here is the link: http://expressjs.com/starter/static-files.html
Now you can directly open the file using the url from the browser like:
window.open('http://localhost:9000/assets/exports/receipt.pdf');
or
res.redirect('http://localhost:9000/assets/exports/receipt.pdf');
should be working.
Second way is to read the file, the data must be coming as a buffer. Actually, it should be recognised if you send it directly, but you can try converting it to base64 encoding using:
var base64String = buf.toString('base64');
then set the content type :
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Length': stat.size
});
and send the data as response.
I will try to put an example of this.
EDIT: You dont even need to encode it. You may try that still. But I was able to make it work without even encoding it.
Plus you also do not need to set the headers. Express does it for you. Following is the Snippet of API code written to get the pdf in case it is not public/static. You need API to serve the pdf:
router.get('/viz.pdf', function(req, res){
require('fs').readFile('viz.pdf', function(err, data){
res.send(data);
})
});
Lastly, note that the url for getting the pdf has extension pdf to it, this is for browser to recognise that the incoming file is pdf. Otherwise it will save the file without any extension.
Usually if you are using phantom to generate a pdf then the file will be written to disc and you have to supply the path and a callback to the render function.
router.get('/pdf', function(req, res){
// phantom initialization and generation logic
// supposing you have the generation code above
page.render(filePath, function (err) {
var filename = 'myFile.pdf';
res.setHeader('Content-type', "application/pdf");
fs.readFile(filePath, function (err, data) {
// if the file was readed to buffer without errors you can delete it to save space
if (err) throw err;
fs.unlink(filePath);
// send the file contents
res.send(data);
});
});
});
I don't have experience of the frameworks that you have mentioned but I would recommend using a tool like Fiddler to see what is going on. For example you may not need to add a content-length header since you are streaming and your framework does chunked transfer encoding etc.
So I'm using Cordova + Sencha Touch for an app and Antair's SQLitePlugin (https://github.com/Antair/Cordova-SQLitePlugin) to import and use an SQLite database in it.
I managed to import my (kinda big) prepopulated database using Antair's importPrepopulatedDatabase ( window.sqlitePlugin.importPrepopulatedDatabase({file:"mydb.db",importIfExists:false}) ) method and it works just fine. The thing is I noticed the app is using twice the size it really needs as it keeps the file after importing it.
I checked and the app works just fine if I delete the file from /cordova/www/db and build again, it keeps the actual db in the app's filesystem I guess, but I can't find a way to programmatically delete that file after it has been imported.
I looked around and found cordova file plugin (https://github.com/apache/cordova-plugin-file/blob/master/doc/index.md), but from what I saw from the docs it only grants read permissions on the www folder, so that won't do it.
Does anyone have any workaround for this? I could really use that extra space.
By using cordova file plugin api you can do this,
please refer this :
deleteFile: function(fileName) {
var that = this;
if (!fileName) {
console.error("No fileName specified. File could not be deleted.");
return false;
}
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function(fileSystem){ // this returns the tmp folder
// File found
fileSystem.root.getFile(fileName, {create: false}, function(fileEntry){
fileEntry.remove(function(success){
console.log(success);
}, function(error){
console.error("deletion failed: " + error);
});
}, that.get('fail'));
}, this.get('fail'));
}
Can anyone provide me an example in PLUNKER that how to load JSON file for karma/jasmine test.I want to read the data from JSON file for the test cases i am writing.I have been searching but nowhere they mentioned clear example on how to do it? I appreciate it if anyone can provide with the example.
You can load an external json data file using require
var data = require('./data.json');
console.log(data);
// Your test cases goes here and you can use data object
Set the path to find your file, in this case my file (staticData.json) is located under /test folder.
jasmine.getFixtures().fixturesPath = 'base/test/';
staticData= JSON.parse(jasmine.getFixtures().read("staticData.json"));
You have to add also the pattern in the karma.conf.js file, something like:
{ pattern: 'test/**/*.json', included: false, served: true}
Do you want to read the JSON file from a webserver or a local file system? No one can give an example of loading from a local file system from Plunker, since it runs in a web browser and is denied access to the file system.
Here is an example of how to load a JSON file from disk in any Node.js program, this should work for Karma/Jasmine:
var fs = require('fs');
var filename = './test.json';
fs.readFile(filename, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.dir(data);
});
I'm trying to replace a PDF file in a Google Drive Folder using a script. Since GAS does not provide a method for adding revisions (versions), I'm trying to replace the content of the file, but all I get is a blank PDF.
I can't use the DriveApp.File class since our Admin has disabled the new API, so I have to use DocsList.File instead.
Input:
OldFile.pdf (8 pages)
NewFile.pdf (20 pages)
Output expected:
OldFile.pdf with the same content as NewFile.pdf
Real Output:
OldFile.pdf with 20 empty pages.
Process:
var old = DocsList.getFileById("####");
var new = DocsList.getFileById("####");
old.replace(new.getContentAsString());
Any ideas, please?
Thanks a lot in advance.
PS.: I also tried calling old.clear() first, but I'd say the problem lies on the getContentAsString method.
The Advanced Drive Service can be used to replace the content of an existing PDF file in Google Drive. This answer also includes an example of how to update a PDF file in a shared Drive.
function overwriteFile(blobOfNewContent,currentFileID) {
var currentFile;
currentFile = DriveApp.getFileById(currentFileID);
if (currentFile) {//If there is a truthy value for the current file
Drive.Files.update({
title: currentFile.getName(), mimeType: currentFile.getMimeType()
}, currentFile.getId(), blobOfNewContent);
}
}
References
https://developers.google.com/apps-script/advanced/drive
https://developers.google.com/drive/api/v3/reference/files/update
An example of using with a shared Drive:
Drive.Files.update({ title: currentFile.getName(), mimeType:
currentFile.getMimeType() }, currentFile.getId(), blobOfNewContent,
{supportsTeamDrives: true});
Try to get it as a blob datatype instead.
I have sucessfully managed to make a file upload system which basically is copying files to a specific folder and save in the database its location. Now i need help with the download part. Imagine my file location is: Files/1306242602661_file1.exe, and in my view i have this:
<g:link controller="fileManager" action="downloadFile">
Download</g:link><br>
I need help with the downloadFile controller. Could you please give me a hint about how to do this, considering my filename is a string:
String fileName = "Files/1306242602661_file1.exe"
Within your controller create an download action with following content:
def file = new File("path/to/file")
if (file.exists()) {
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "filename=${file.name}")
response.outputStream << file.bytes
return
}
// else for err message
You can render a file. see http://grails.org/doc/2.4.x/ref/Controllers/render.html
render file: new File ("path/to/file.pdf"), fileName: 'myPdfFile.pdf'