Laravel 4: File Upload says success not showing in folder - file

I'm trying to get a simple image file to upload, then move it to a designated folder, and though I get no error messages, and everything says it works, it won't show up in any folder. The code in question is:
$destination = public_path().'/auction_img/';
$filename = $auction->id;
if (Input::hasFile('image')) {
$file = Input::file('image');
try{
$uploadSuccess = $file->move($destination, $filename.$file->getClientOriginalExtension());
}catch(Exception $e){
error_log('Exception: '.$e->getMessage());
}
if($uploadSuccess){
error_log("YAY!");
}
}
I'm not getting an exception, and I am getting the "YAY" in the error_log. But it won't show up whatever I do. Any ideas? I also checked my php.ini and it has a max size of 20M but the file is only about .5MB

Looks like it's not going where you think it is going.
First of all
try{} catch() {}
Doesn't work on Laravel. You have to set a handler:
App::error(function(Exception $exception)
{
Log::error($exception);
});
Then do a full log of your move to see if it is really going where you need it to:
$destination = public_path().'/auction_img/';
$filename = $auction->id;
if (Input::hasFile('image')) {
$file = Input::file('image');
$uploadSuccess = $file->move($destination, "$filename.".$file->getClientOriginalExtension());
if($uploadSuccess)
{
error_log("Destination: $destination");
error_log("Filename: $filename");
error_log("Extension: ".$file->getClientOriginalExtension());
error_log("Original name: ".$file->getClientOriginalName());
error_log("Real path: ".$file->getRealPath());
}
else
{
error_log("Error moving file: ".$file->getClientOriginalName());
}
}
Also check if the original file is where it is supposed to be.
According to the comments, your move should be:
$uploadSuccess = $file->move($destination, "$filename.".$file->getClientOriginalExtension());
Check if $destination points to your public folder, it must look something like:
/var/www/site/public/auction_img/
Check if public_path() returns /var/www/site/public/ and if it doesn't you can use this in place of it:
$destination = app()->make('path.public').'/auction_img/'

$uploadSuccess in Laravel 4.0 at least, is not a boolean. It returns the file object after it has been moved (it returns $file, so it can be chained). This object cannot reliably be cast to a boolean (Symfony is raising an exception for me if I try to use it in an if-statement like you have).
If the file fails to be moved, then an exception will be raised. If an exception is raised, then you know the file has not been moved and remains where it is. As such, that leaves $file as a valid Symfony file object, and so your processing will continue with the file where it first landed.
So whether the file successfully moves or not, your "YAY!" is always in the execution path. You catch the exception if the move fails, log it, then fail to take any further action on the exception.

Related

Xamarin.Android: Write something into a file and be able to open it with the computer afterwards

I am trying to write some kind of an external config file for my Xamarin.Android-application. Just .txt and this only needs to contain several strings, so no rocket science^^
e.g. (Sample Goal/Hopefully final content of the text file:)
[TestSection]
test=12345
I tried it with a tutorial and the following code:
//This code snippet is one example of writing a string to a UTF-8 text file and into the internal storage directory of an application:
public void SaveSomethingIntoExternalTextFile(string toWrite)
{
var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "config.txt");
using (var writer = System.IO.File.CreateText(backingFile))
{
writer.WriteLine(toWrite);
}
}
But unfortunately this has no effect. As my only app-specific path is
Phone\Android\data\com.<company_name>.<application_name>\files
I cannot find any file there after running the code above. And even if I create a new file with the computer in the given path, name it as written (config.txt) and run the given code again, still nothing happens (so the string which's passed as parameter into the method unfortunately isn't written into that file as tried).
Just for the sake of completeness, my test application is pretty simple:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SaveSomethingIntoExternalTextFile("[TestSection]");
SaveSomethingIntoExternalTextFile("test="+12345);
}
Can anyone maybe help? What am I doing wrong?
Would be really happy about every answer, thanks in advance and
Best regards
P.S.: If I open the by computer generated text file, even if in the file directory its displayed correctly, the heading of the file says config[1].txt, opening again config[2].txt and so on. Or does that not matter/has nothing to do with my attempt above?
If you use System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), the path is like
/data/data/App3.App3/files/config.txt
It means that you save it in internal storage, you could not see it without root permission,if you want to see it, you can save it in external storage.
public void SaveSomethingIntoExternalTextFile(string toWrite)
{
string path = Android.App.Application.Context.GetExternalFilesDir(null).ToString();
string filepath = Path.Combine(path, "text.txt");
using (var writer = System.IO.File.CreateText(filepath))
{
writer.WriteLine(toWrite);
}
}
The path like :
/storage/emulated/0/Android/data/App3.App3/files/text.txt
Okay via Debugging, I found out that indeed he does write the value, at least I can retrieve it with the following function (I changed the type of the value to integer as in my tutorial (https://learn.microsoft.com/de-de/xamarin/android/platform/files/index#reading-or-writing-to-files-on-internal-storage ) it was integer as well):
//This code snippet provides one way to read an int value that was stored in a text file:
public int ReadSomethingFromTextFile()
{
var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "config.txt");
if (backingFile == null || !System.IO.File.Exists(backingFile))
{
return 0;
}
int count = 0;
using (var reader = new StreamReader(backingFile, true))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (int.TryParse(line, out var newcount))
{
count = newcount;
}
}
}
return count;
}
Nevertheless, I cannot find the written file. Is the Path System.Environment.SpecialFolder.Personal the right one? Or does this point to root directory, where I am always seeking in some kind of user folder?
Because when looking with the debugger what's inside backingFile, it's
/data/data/com.<company_name>.<application_name>/files/config.txt,
and as written in the post above, the only app-specific path I can access via explorer is
Phone/Android/data/com.<company_name>.<application_name>/files.
I read something about having to root my phone in order to be able to access this path? Makes no sense right?
Isn't there some kind of shared folder (/path), whichs accessable not only by application/operating system but also from outside?

Copying a file to the root path in Codename One

In my code I am prompting the user to load a json file.
I am then attempting to copy this file into an sqlite database.
Once I have the data I am then able to manipulate it as needed - but I need to get it there in the first place.
So step 1 is to get the data in.
I have progressed as far as prompting the user to navigate to the file they want - but when I try and read the file I get this error ..
ERROR: resources must reside in the root directory thus must start with a '/' character in Codename One! Invalid resource: file:///tmp/temp3257201851214246357..json
So I think that I need to copy this file to the root directory
I cannot find a link that shows me how to do this.
Here is my code so far ...
case "Import Script":
try
{
JSONParser json = new JSONParser();
if (FileChooser.isAvailable()) {
FileChooser.showOpenDialog(".json", e2-> {
String file = (String)e2.getSource();
if (file == null) {
home.add("No file was selected");
home.revalidate();
} else {
home.add("Please wait - busy importing");
home.revalidate();
String extension = null;
if (file.lastIndexOf(".") > 0) {
extension = file.substring(file.lastIndexOf(".")+1);
}
if ("json".equals(extension)) {
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream fis = fs.openInputStream(file);
try(Reader r = new InputStreamReader(Display.getInstance().getResourceAsStream(getClass(), file), "UTF-8"))
{
Map<String, Object> data = json.parseJSON(r);
Result result = Result.fromContent(data);
...... I progress from here
The error is occurring on this line ...
try(Reader r = new InputStreamReader(Display.getInstance().getResourceAsStream(getClass(), file), "UTF-8"))
If I hard code a filename and manually place it in the /src folder it works ... like this ...
try(Reader r = new InputStreamReader(Display.getInstance().getResourceAsStream(getClass(), '/test.json'), "UTF-8"))
But that defeats the purpose of them selecting a file
Any help would be appreciated
Thanks
I suggest watching this video.
It explains the different ways data is stored. One of the core sources of confusion is the 3 different ways to store files:
Resources
File System
Storage
getResourceAsStream returns a read only path that's physically embedded in the jar. It's flat so all paths to getResourceAsStream must start with / and must have only one of those. I would suggest avoiding more than one . as well although this should work in theory.
The sqlite database must be stored in file system which is encapsulated as FileSystemStorage and that's really the OS native file system. But you can't store it anywhere you want you need to give the DB name to the system and it notifies you where the file is stored and that's whats explained in the code above.

Multiple foreach loop containers in SSIS

I am working on a package which requires multiple data flow task within multiple foreach loop containers. The issue arises when i try and run the whole package. The first data flow task within the first for each loop container executes successfully but the flow doesn't enter the other for each loop containers. the initial package looks like :
Initial Package
Package after execution
I want to know what changes are required to make the data flow task within the other containers to execute.(All variables have a package scope). For each loop containers are running successfully when kept in different packages.
Looks like it is entering into the other for loops as well, however it is not finding right set of Files to process, please check your for collection of objects.
Also you have expressions in foreach loops, so check whether they are evaluating correctly.
i.e it may have *.txt, but you don't have any such files in the folder. so only foreach loop is executing but not the data flow.
You might want to check to see if anything that is being done in the first for loop is causing the expressions in the other for loops to evaluate incorrectly.
string[] arr = new string[] { "https://sim.oecd.org/Export.ashx?lang=En&ds=TFI&d1c=hinoecd&d2c=atg&d2cc=bp",
"https://sim.oecd.org/Export.ashx?lang=En&ds=TFI&d1c=hinoecd&d2c=bhs&d2cc=bp",
"https://sim.oecd.org/Export.ashx?lang=En&ds=TFI&d1c=hinoecd&d2c=bhr&d2cc=bp" };
try
{
string fileName = Dts.Variables["User::filename"].Value.ToString(), myWebString = null, myLocalPath = null;
WebClient myWebClient = new WebClient();
foreach (string myURI in arr)
{
myWebString = myURI + fileName;
myLocalPath = "c:\sql\" + fileName;
myWebClient.DownloadFile(myWebString, myLocalPath);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
Dts.Events.FireError(18, "The process failed", ex.ToString(), "", 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
my code is working fine but only one url how to take different url to download files how can i d

CakePHP - CakeResponse::File extremely slow

I need to serve files to authenticated users and recognise that using PHP will include a performance penalty, however what I've experienced so far seems to be unworkable.
I have a very simple controller action which sends the file:
public function view($id = null) {
$id = $id | $this->params->named['id'];
if (!$this->Attachment->exists($id)) {
throw new NotFoundException(__('Invalid attachment'));
}
$this->autoRender = false;
$this->Attachment->recursive = -1;
$file = $this->Attachment->findById($id);
$this->response->file(APP . DS . $file['Attachment']['dir']);
return $this->response;
}
A small (55 KB) PNG file takes 8 seconds to load using this method, where as if I move the file to the webroot directory and load it directly it takes less than 2.5 seconds. From looking at Chrome Dev Tools, the 'Receiving' part of the response is taking > 7s (compared with 1.5s direct).
A medium sized PDF file (2.5MB) takes over 2 minutes through CakeResponse, compared to ~4s directly. Surely I must be missing something in my controller action as this must be unworkable for anyone?
EDIT: CakePHP version is 2.4.1.
Thanks to the suggestion to use Xdebug I was able to quickly track down the problem.
In CakeResponse, there is the following function:
/**
* Flushes the contents of the output buffer
*
* #return void
*/
protected function _flushBuffer() {
//#codingStandardsIgnoreStart
#flush();
#ob_flush();
//#codingStandardsIgnoreEnd
}
Obviously with the error suppression operator the calls to flush and ob_flush would not normally cause a problem.
However, I also have Sentry as a remote debugging tool installed. This ignores the error suppression operator, reports that there is no buffer to flush (because ob_start has not been called) and in doing so outputs the contents of the file to the log file!

Wait for file to delete, then copy a folder

I have a couple of scripts that have to sync a folder from the network server, to the local terminal server, and lastly into the %LOCALAPPDATA%. I need to first check if a folder is being synced (this is done by creating a temporary COPYING.TXT on the server), and wait until that is removed, THEN copy to %LOCALAPPDATA%.
Something like this:
Server-side script executes, which syncs my folder to all of my terminal servers.
It creates a COPYING.TXT temporary file, which indicates the sync is in progress. Once the sync is finished, the script removes the COPYING.TXT
If someone logs on during the sync, I need a script to wait until the COPYING.TXT is deleted I.E the sync is finished, then resume the local sync into their %LOCALAPPDATA%.
do {
cp c:\folder\program $env:LOCALAPPDATA\
} while ( !(test-path c:\folder\COPYING.txt) )
(So that copies the folder while the file DOESN'T exist, but I don't think that exits cleanly)
Or:
while ( !(test-path c:\folder\COPYING.txt) ) {
cp c:\folder\program $env:LOCALAPPDATA\ -recurse -force
if ( !(test-path c:\folder\program) ) {return}
}
But that script quits if the COPYING.TXT exists. I think I need to create a function and insert that function within itself, or a nested while loop, but that is starting to make my head hurt.
As Mosser Lee said, try using the FileSystemWatcher class. Here is a working sample.
#Create the Copying.txt file
"test"|Out-File Copying.txt
#Create a filesystemwatcher
$watcher = New-Object System.IO.FileSystemWatcher
#Give it the root path to monitor
$watcher.Path = $pwd
#The matching pattern
$watcher.Filter = "Copying.txt"
#Monitor subfolder or not
$watcher.IncludeSubdirectories = $true
#Setup event and save a ref
$evt = Register-ObjectEvent $watcher Deleted FileDeleted -Action {
#Stuff it into the global space just so you can inspect it
$global:SomeVar = $Event
Write-Host ("{0} deleted at {1}" -f $Event.SourceEventArgs.FullPath, $Event.TimeGenerated)
}
Remove-Item Copying.txt
This gives output like "H:\Copying.txt deleted at 6/12/2014 3:01:48 PM" when the file is deleted. It also sets a global variable $global:SomeVar if you wanted to look at the properties in depth.
$global:SomeVar
ComputerName :
RunspaceId : 1ab5089e-1734-4b92-8bab-9de4df78ada2
EventIdentifier : 2
Sender : System.IO.FileSystemWatcher
SourceEventArgs : System.IO.FileSystemEventArgs
SourceArgs : {System.IO.FileSystemWatcher, Copying.txt}
SourceIdentifier : FileDeleted
TimeGenerated : 6/12/2014 3:01:48 PM
MessageData :
Don't forget to unregister the event as it will continue to run until you close the session even if you set $watcher to null.
Unregister-Event $evt.Id
Did you have a try to use c# FileSystemWatcher, to monitor the target folder, when change event raised, then check the target file, if it no exits, your expected time is comming: do it.

Resources