How to get uploaded file name after rename in Fat-Free Framework? - fat-free-framework

I use this to save uploaded file
$web = \Web::instance();
$uploadPath=$f3->get('uploadFolder');
$f3->set('UPLOADS',$uploadPath);
$overwrite = true;
$slug = true;
$files = $web->receive(function($file,$formFieldName){
if(file_exists($file['name'])){
//$file['name'] = $f3->get('uploadFolder').'rename.jpg'; // this is error, how to get path from config.ini here?
$file['name'] = 'assets/img/upload/rename.jpg';
move_uploaded_file($file['tmp_name'], $file['name']);
return false;
}else{
return true;
}
},
$overwrite,
$slug
);
$savedFile=array_keys($files)[0];
This only get the file path before rename, how can I get the path after rename?
And how to get config in callback function?

You don't need to get any uploads directory from config or call move_uploaded_file manually yourself.. that's all part of the $web->receive method.
The $files array will contain the full final path (incl. the renamed file name).
When you return true in the callback function, the uploaded file is moved to the upload folder defined in the UPLOADS F3 variable. Just check for file sizes, mime-types etc. in the callback function if you need. That's all you usually need to do.

Related

How to make gulp-newer work with gulp-rev?

The setup is as simple as this:
gulp.task('rev-js', function() {
return gulp.src('/js/main.js, {base: '.'})
.pipe(newer('_build'))
.pipe(rev())
.pipe(gulp.dest('_build'))
.pipe(rev.manifest())
.pipe(gulp.dest('_build/rev/js'));
});
gulp-newer obviously doesn't work here since the destination file gets a different name. Any workaround to make gulp-newer (or gulp-changed) work in this case?
In the gulp-newer options documentation I read that it supports passing in a configuration object instead of the destination. In that configuration object you can specify a mapping function from old to new files. So instead of
newer('_build')
you can write
newer({dest: '_build', map: mappingFn})
The mapping function takes the relative name of the file and expects it to return a translated name - see the index.js file. You can define a function that uses the previously generated rev-manifest.json manifest to look up the correct filename. Id put something along these lines in your build script (not tested):
gulp.task('rev-js', function() {
// get the existing manifest
// todo: add logic to skip this if file doesn't exist
var currentManifest = JSON.parse(fs.readFileSync('rev-manifest.json', 'utf8'));
// mapping function for gulp-newer
function mapToRevisions(relativeName) {
return currentManifest[relativeName]
}
return gulp.src('/js/main.js, {base: '.'})
.pipe(newer({dest: '_build', map: mapToRevisions}))
.pipe(rev())
.pipe(gulp.dest('_build'))
.pipe(rev.manifest())
.pipe(gulp.dest('_build/rev/js'));
});
May I suggest gulp-newy in which you can manipulate the path and filename in your own function. Then, just use the function as the callback to the newy(). This gives you complete control of the files you would like to compare.
This will allow 1:1 or many to 1 compares.
newy(function(projectDir, srcFile, absSrcFile) {
// do whatever you want to here.
// construct your absolute path, change filename suffix, etc.
// then return /foo/bar/filename.suffix as the file to compare against
}

how to modify config files using gulp

I use gulp to configure complex local setup and need to auto-edit files.
The scenario is:
determine if certain file contains certain lines after certain other line (found using regular expression)
if line is not found, insert the line.
optionally, delete some lines found in the file.
I need this to amend system configuration files and compile scenarios.
What would be the best way to do it in gulp?
Gulp is plain javascript. So what I would do if I were you is to create a plugin to pipe to the original config file.
Gulp streams emit Vinyl files. So all you really got to do is to create a "pipe factory" that transforms the objects.
It would look something like this (using EventStream):
var es = require('event-stream');
// you could receive params in here if you're using the same
// plugin in different occasions.
function fixConfigFile() {
return es.map(function(file, cb) {
var fileContent = file.contents.toString();
// determine if certain file contains certain lines...
// if line is not found, insert the line.
// optionally, delete some lines found in the file.
// update the vinyl file
file.contents = new Buffer(fileContent);
// send the updated file down the pipe
cb(null, file);
});
}
gulp.task('fix-config', function() {
return gulp.src('path/to/original/*.config')
.pipe(fixConfigFile())
.pipe(gulp.dest('path/to/fixed/configs');
});
Or you can use vinyl-map:
const map = require('vinyl-map')
const gulp = require('gulp')
const modify = map((contents, filename) => {
contents = contents.toString()
// modify contents somehow
return contents
})
gulp.task('modify', () =>
gulp.src(['./index.js'])
.pipe(modify)
.pipe(gulp.dest('./dist'))
})

Google chrome extensions for managing Downloads

I am trying to create an extension which puts all the pdf files downloaded by user through browser into a separate directory. Any Api by which can do this or some help on how I can do it would be helpful.
While you cannot easily write to an arbitrary path, you can redirect all PDF files into a subfolder of Downloads folder.
Check out onDeterminingFilename event of chrome.downloads and Filename Controller sample extension. Since you can indicate a relative path instead of a plain filename, this should work.
Note that the file's MIME type should be available in onDeterminingFilename, you can use that.
Code example, as requested:
var folder = "PDF_downloads";
chrome.downloads.onDeterminingFilename.addListener(
function (item, suggest) {
if(isPDF(item)) suggest({filename: folder + "/" + item.filename});
else suggest();
}
);
function isPDF(item){
if(item.mime === "application/pdf") return true;
else if (item.filename.match(/\.pdf$/i)) return true;
else return false;
}
This will not override that the browser tries to open the PDF itself instead of downloading, but attempting to download will suggest that folder.

as3 selecting a file dynamically

i need to select a video file and convert it to a byte array. the file i am trying to select has been recorded by the cameraUi interface. i can get the path to the file using
fileName = media.file.url;
readFileIntoByteArray(filePath, inBytes);
when i am passing it into the byte array i need to select directory first and then pass in the the rest of the path.
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = File.userDirectory;
inFile = inFile.resolvePath(fileName);
trace (inFile.url);
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
}
this leads to duplication of the first part of the path.
i want to keep this dynamic as it will be run on different devices. i hard coded the file into the the variables section of flash debugger and it worked also i get an error if i leave out file.userDirectory
thanks in advance any help would be appreciated
You should always use File.applicationStorageDirectory instead of File.userDirectory. Due to security risk will vary to vary different device. File.applicationStorageDirectory will work any device.
Robust way of working with filepath
var firstPartPath:String = File.applicationStorageDirectory.nativePath;
var fullPath:String = File.applicationStorageDirectory.resolvePath("fileName.jpg").nativePath;
var expectedPath:String = fullPath.replace(firstPartPath,""); // "/fileName.jpg"
Here expectedPath value you should pass around your project instead of hard code value like c:\users\XXXX\ and save into database also use expectedPath value.
For latter access file just pass only expectedPath.
var inFile:File = File.applicationStorageDirectory.resolvePath(expectedPath);
Needn't worry about forward and backword slashes. File resolvePath() take care for you.
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = File.applicationStorageDirectory.resolvePath(fileName);
trace (inFile.url);
trace (inFile.nativePath);
trace (inFile.exists); //if file present true else false.
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
}

Phonegap file writer is not working, cannot truncate file content

I am using phonegap file reading functionality, once i read the content and i will do some functionality with that content, once that over i am calling file truncate functionality. In that i can't truncate any value. Help me to fix this issue.
removeFileContent();
function removeFileContent(){
console.log("Inside remove file content");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileTruncate, onProcessFailure);
};
function gotFileTruncate(fileSystem){
console.log("Inside get file path for remove content");
/** Function to get file path */
filePath = getFilePath(device.platform);
console.log("Device File Path to remove content-->"+this.filePath);
fileSystem.root.getFile(filePath, null, gotFileEntryTruncate, onProcessFailure);
}
function gotFileEntryTruncate(fileEntry){
globals.raiseLog("Inside file to truncate call");
globals.raiseLog("File Name-->"+fileEntry.name);
fileEntry.createWriter(gotFileWriter, onProcessFailure);
}
function gotFileWriter(writer){
globals.raiseLog("Inside file writer to truncate file content");
globals.raiseLog("Content length-->"+writer.length);
//writer.truncate(10);
writer.onwriteend = function(evt) {
writer.truncate(0);
writer.onwriteend = function(evt) {
};
};
writer.write("");
globals.raiseLog("Content length after truncate-->"+writer.length);
}
In the above gotFileWriter() if i check for writer.length its still showing some count. I dont know how come we can check the file gets empty. I having some text inside that file. Need to clear the file when i finish the reading of the file. I am calling removeFileContent() after i finish the reading functionality. Kindly help.
The way your code is written you may get a false positive that the file still has contents in it. Move your:
globals.raiseLog("Content length after truncate-->"+writer.length);
into your onwriteend function as the write call is async and may not finish before your log is printed.