I am using Appcelerator Titanium 3.0.2 to allows user to watch/download videos&audios. Here is part of code to get the file object and play the audio.
var filename = self.url.substring(self.url.lastIndexOf('/')+1);
var file = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory,filename);
if(!file.exists())
self._download(self.url, filename, Ti.Filesystem.tempDirectory, function(){
setAudUrl(file.nativePath);
timeBar.max = audPlayer.duration*1000;
prgHandle = setInterval(updateProgressBar,10000);
audPlayer.play();
audCtrlBar.show();
loading.hide();
},
function(_progress,_position){
httpClient=_position;
loading.show();
},
function(){
noLabel.show();
loading.hide();
});
else {
setAudUrl(file.nativePath);
timeBar.max = audPlayer.duration*1000;
prgHandle = setInterval(updateProgressBar,10000);
audPlayer.play();
audCtrlBar.show();
}
This code is working, but my question is how to remove the file when the user exist the app. Since Apple required that file in /tmp directory will be removed after user exist the app. Anyone can help? Thanks.
You could use Titanium's application events pause and paused. They are called when the app becomes inactive but this only works on iOS.
Titanium.App.addEventListener('pause' /* or paused, see docs */, function() {
var dir = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory, 'tmpDownloads'); // ensure that you use the same folder for storing the downloaded files. A separate folder is easier to remove.
if(dir.exists() && dir.isDirectory()) {
dir.deleteDirectory(true); // true removes recursively the directory and its contents
}
});
You need to create the directory again when resume-ing the app.
Related
I have a file upload form in on of my blade files.
However when I upload the file I see its saving the file to /storage//Applications/MAMP/tmp/php/phpIVfP2L.mp4 how do I set this upload to be saved to a specific location like I want them saved in the Laravel public folder that is in the Laravel root directory so the path would be /public/trainingvideos
Below is my controller code where my file upload code is
public function addtraining(Request $req) {
//Save to a mysql database
//print_r($req->input());
$pwdata = new AddTraining;
$pwdata->userid = $req->userid;
$pwdata->video_title = $req->trainingtitle;
$pwdata->video_description = $req->trainingdesc;
$pwdata->video_url = $req->trainingvideo;
if($req->hasFile('trainingvideo')) {
// Let's do everything here
if($req->file('trainingvideo')->isValid()) {
//
$validated = $req->validate([
'trainingvideo' => 'mimes:mp4,mov|max:10000',
]);
$extension = $req->trainingvideo->extension();
$req->trainingvideo->storeAs('public_path()/public/trainingvideos', $req->trainingvideo.".".$extension);
$url = Storage::url($req->trainingvideo.".".$extension);
$pwdata->video_url = $url;
//Session::flash('success', "Success!");
}
}
//abort(500, 'Could not upload video :(');
$pwdata->save();
The /tmp directory is where files are temporarily stored when uploaded.
In your controller you need to go about actually storing that file, the docs cover this in depth; https://laravel.com/docs/7.x/requests#storing-uploaded-files
It's worth mentioning that if you leave the files in your tmp directory, they will be garbage collected at some point and so this is not a safe location to store files.
My current project requires a file download. The file is auto generated and has an unfriendly name when it's saved, so we are changing the file name to something easier to read on download.
For example if a user downloads a file called 324343242342.pdf we change it to Lesson1.pdf or something for the one that's saved on their computer.
I'm having some trouble with ie11 with this. I know that the download attribute doesn't work on ie11, so for that sake we are using blobs and things are working fine for download purposes across browsers, but I'm not sure how to change the name of the file in ie11.
In all other browsers I just do <a href="#" :download="new_file_name"> to call a small file name calculating method in the vue component, but this doesn't work for ie11 because the "download" attribute doesn't work there.
Anyone have any idea how to go about editing that name in ie11 as well? I'm only finding answers for fixing the download functionality in general, nothing about setting a file name.
Thank you!
You have to do something similar to https://github.com/kennethjiang/js-file-download/blob/master/file-download.js
function downloadFile (data, filename, mime) {
const blob = new Blob([data], { type: mime || 'application/octet-stream' })
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// For IE
window.navigator.msSaveBlob(blob, filename)
} else {
// For other browsers
const blobURL = window.URL.createObjectURL(blob)
const tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = blobURL
tempLink.setAttribute('download', filename)
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank')
}
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
window.URL.revokeObjectURL(blobURL)
}
}
I'm using Laravel 5.6, jQuery 3.3.1, bootstrap 3.3.7, and PHP 7.1.4
I need to be able to allow users to upload files and pictures, basically jpg, gif, png, and pdf. I am using the public disk and storing the files in storage/app/public/folder_name where folder_name is defined in an env file
FILESYSTEM_DRIVER=public
PO_FILE_FOLDER=purchase_orders
INSURANCE_FILE_FOLDER=insurance
NOTE_FILE_FOLDER=notes
RENTAL_AGREEMENT_FILE_FOLDER=rental_agreements
SIGNATURES=signatures
They are then defined in config/app
'insurance_file_folder' => env('INSURANCE_FILE_FOLDER', ''),
'po_file_folder' => env('PO_FILE_FOLDER', ''),
'note_file_folder' => env('NOTE_FILE_FOLDER', ''),
'rental_agreement_file_folder' => env('RENTAL_AGREEMENT_FILE_FOLDER', ''),
'max_image_width' => env('MAX_IMAGE_WIDTH', 500),
'filesystem_driver' => env('FILESYSTEM_DRIVER', 'local'),
When I upload image files they upload to the appropriate folder but when I try to upload pdf files the system creates a new folder named as what I'm naming the file and the pdf is in the new folder with a random name. I'm using the exact same code to upload both images and pdf files so I can't figure out why it works for one but not the other.
Here is my controller code
public function store(PurchaseOrderRequest $poRequest, Customer $customer)
{
$purchaseOrder = $customer->purchaseOrders()->create($poRequest->except('attachment'));
if ($poRequest->hasFile('attachment')) {
$purchaseOrder->saveFile(config('app.po_file_folder', ''), $poRequest->file('attachment'));
}
return redirect()->action('CustomerController#edit', $customer)->with('alert', 'Purchase Order created.');
}
My model PurchaseOrder saveFile code
public function saveFile($folder_name, $file)
{
// if file submited then check if file already exists, if so delete file and create new file
$file_name = $this->createFileName();
File::removeFiles($folder_name.'/'.$file_name, FALSE);
$file_name = $file_name.'.'.$file->getClientOriginalExtension();
$file = File::resize($file);
$this->attachment_path = $folder_name.'/'.$file_name;
Storage::disk(config('app.filesystem_driver', ''))->put($this->attachment_path, $file);
$this->save();
}
public function createFileName()
{
$file_name = 'po_'.$this->customer->code.'-'.$this->customer->id.'_'.$this->po_number.'-'.$this->id;
return $file_name;
}
My File helper code
public static function resize($file)
{
$resized_file = $file;
if (strtolower($resized_file->getClientOriginalExtension()) != 'pdf') {
// resize file if it is not pdf (file is photo)
// get image size then resize largest size to size limit - dont upsize if image is smaller than max size
list($width, $height) = getimagesize($resized_file);
if ($width > $height) {
$resized_file = Image::make($resized_file)->resize(config('app.max_image_width', ''), null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode($resized_file->getClientOriginalExtension(), 60);
} else {
$resized_file = Image::make($resized_file)->resize(null, config('app.max_image_width', ''),function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode($resized_file->getClientOriginalExtension(), 60);
}
}
return $resized_file;
}
public static function removeFiles($file_name, $ext_included = FALSE)
{
if ($ext_included == TRUE) {
// remove specific file
if (Storage::disk(config('app.filesystem_driver', ''))->exists($file_name)) {
Storage::delete($file_name);
}
} else {
// remove file with any extension
$ext = array('.pdf', '.jpg', '.jpeg', '.gif', '.png');
for ($cnt = 0; $cnt <= 4; ++$cnt) {
if (Storage::disk(config('app.filesystem_driver', ''))->exists($file_name.$ext[$cnt])) {
Storage::delete($file_name.$ext[$cnt]);
}
}
}
}
I realize the code may be a little confusing use the env variables but I'm trying to limit the pain in the event I need to change the folder name or move the files outside of the app. The application will have very few users maybe 3 or 4 and I don't anticipate a lot of files being uploaded which is why I'm storing the files in the application structure.
This is my first Laravel app and I put this code together using the docs and many a many different tutorials. It took a while but eventually I got it to work for images. So if you see things that don't look standard or good practice I welcome any pointers.
Thanks for taking the time to read this, any help is appreciated!
I had to use two different approaches to saving files in the system based on if the file was an image or pdf. I do some processing (resizing) on images before putting them into my storage folders with Intervention Image. This in turn returns a different object type than the raw uploaded file, because of this some of the commands to add the file (after processing) will not work.
So if I'm storing a pdf file I use:
$file->storeAs($folder_name, $file_name, config('app.filesystem_driver', ''));
If I'm storing an image that I have used Intervention Image on then I use:
Storage::disk(config('app.filesystem_driver', ''))->put($this->attachment_path, $file);
I couldn't find one command that worked for both so I just check the extension before storing. Not sure if this is the "right way" but it got the job done.
I'm running into the following problem with requirejs and usemin:
I want to setup a multipage application, where I dynamically load modules that only contain page specific functionality (e.g. about -> about.js, home -> home.js). I could go ahead and pack everything in a single file, but that just leads to a bigger file size and overhead on functionality that isn't necessary on each site! (e.g. why would I need to load a carousel plugin on a page that doesn't have a carousel!)
I checked out the example https://github.com/requirejs/example-multipage-shim
That is in fact a great way to deal with it, until I bring usemin into the game. After revving the filenames the src path of each script tag is updated, but what about the dependencies?
<script src="scripts/vendor/1cdhj2.require.js"></script>
<script type="text/javascript">
require(['scripts/common'], function (common) {
require(['app'], function(App) {
App.initialize();
});
});
</script>
In that case, require.js got replaced by the revved file 1cdhj2.require.js. Great!
But the required modules "common" and "app" no longer work since common became 4jsh3b.common.js and app became 23jda3.app.js!
What can I do about this? Thanks for your help!
(Also using Yeoman, btw)
It's a tricky problem and I'm sure somebody else fixed in in a more elegant way, but the following works for me.
I might publish this as a grunt plugin once it's a little more robust.
Taken from my Gruntfile:
"regex-replace": {
rjsmodules: { // we'll build on this configuration later, inside the 'userevd-rjsmodules' task
src: ['build/**/*.js'],
actions: []
}
},
grunt.registerTask('userevd-rjsmodules', 'Make sure RequireJS modules are loaded by their revved module name', function() {
// scheduled search n replace actions
var actions = grunt.config("regex-replace").rjsmodules.actions;
// action object
var o = {
search: '',
replace: '', //<%= grunt.filerev.summary["build/js/app/detailsController.js"] %>
flags: 'g'
};
// read the requirejs config and look for optimized modules
var modules = grunt.config("requirejs.compile.options.modules");
var baseDir = grunt.config("requirejs.compile.options.dir");
var i, mod;
for (i in modules) {
mod = modules[i].name;
revvedMod = grunt.filerev.summary[baseDir + "/" + mod + ".js"];
revvedMod = revvedMod.replace('.js', '').replace(baseDir+'/','');
o.name = mod;
o.search = "'"+mod+"'";
// use the moduleid, and the grunt.filerev.summary object to find the revved file on disk
o.replace = "'"+revvedMod+"'";
// update the require(["xxx/yyy"]) declarations by scheduling a search/replace action
actions.push(o);
}
grunt.config.set('regex-replace.rjsmodules.actions', actions);
grunt.log.writeln('%j', grunt.config("regex-replace.rjsmodules"));
grunt.task.run("regex-replace:rjsmodules");
}),
You can also use requirejs' map config to specify a mapping between your original module and your revved one.
Filerev outputs a summary object containing a mapping of all the modules that were versioned and their original names. Use grunt file write feature to write a file in AMD way with the contents being the summary object:
// Default task(s).
grunt.registerTask('default', ['uglify', 'filerev', 'writeSummary']);
grunt.registerTask('writeSummary', 'Writes the summary output of filerev task to a file', function() {
grunt.file.write('filerevSummary.js', 'define([], function(){ return ' + JSON.stringify(grunt.filerev.summary) + '; })');
})
and use this file in your require config so that the new revved modules are used instead of old ones:
require(['../filerevSummary'], function(fileRev) {
var filerevMap = {};
for (var key in fileRev) {
var moduleID = key.split('/').pop().replace('.js', '');
var revvedModule = '../' + fileRev[key].replace('.js', '');
filerevMap[moduleID] = revvedModule;
}
require.config({
map: {
'*': filerevMap
}
});
The filerevMap object that I created above is specific to my folder structure. You can tweak it as per yours. It just loops through the filerev summary and makes sure the keys are modified as per your module names and values as per your folder structure.
"EXPORTED_SYMBOLS is not an array" Exception flagged when tried to use Components.utils.import("chrome://app/content/app1.js");.
I have a XUL application created and from one of the JS File(say app.js) I tried to include the other JS File as shown above.
Both app.js and app1.js are placed in content folder and also in chrome.manifest file following line is added
"content app content/"
In other JS File (app1.js), I have exported symbols like
var EXPORTED_SYMBOLS = ["Fooinstance"];
var Fooinstance = {
foo: function() {
...
}
}
In app.js,
Components.utils.import("chrome://app/content/app1.js");
// Error: chrome://app/content/app1.js - EXPORTED_SYMBOLS is not an array
...
Fooinstance.foo();
I am running this XUL app on XULRunner 17.0.1 win32 libraries.
I looked through the code in this link https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Using
It did not help and if I include it as resource it works however I do not want to include it as part of resource.
Could you someone point out what mistake would be ?
I had this same problem, and I solved it:
1) changing the file extension (.js) by .jsm
2) Adding a first line on your module exporting classes to share. EG:
var EXPORTED_SYMBOLS = ["Xobject"];
function Xobject(){
}
Xobject.prototype.stop = function() {
return 'stop';
}
Xobject.prototype.run = function() {
return 'running';
}
3) Calling this way
Components.utils.import('resource://gre/modules/Services.jsm' );
Components.utils.import("chrome://myFirstAddOn/content/Xobject.jsm");
var myXobject = new Xobject();
alert(myXobject.run());
Hope it help u
For anyone else getting this, another possible reason is a circular dependency. My case was a little different, but I had two JSM files each using Components.utils.import to import each other. Then I got this error in one of them.