How to create file in current system from within Grails controller action and save data fetched from database? - database

In my Grails application I need to create a file in current system in which I need to save information fetched from table in database. How to do this from within controller action? I don't have any idea of it.
I have created file as
File file=new File("file name.txt")
file.createNewFile();
then I have wrote values of MySQL database table fields in it as:
file<<patient.id
file<<patient.name
.
.
.
it stores data like continuous text but I want to have a .doc file in which data should get stored in table. I found Apache's POI for creating doc file but I am not getting how it works and how I should use it.

Not sure exactly what you want to store in a file but below is an example of how to easly write a String to a file using Apache-commons-io Which should be included in grails
import org.apache.commons.io.FileUtils;
class SomeController{
def writeToFile = {
def data = getSomeStringData();
def fileStore = new File("./path/to/files/ControllerOutput_${new Date()}.txt");
fileStore.createNewFile();
FileUtils.writeStringToFile(fileStore, data);
println("your file was created # {fileStore.absolutePath} and is ${fileStore.length()} bytes");
}
}
Does this help? If not, you need to explain exactly what your looking for.

This is a comment to Michael's answer (unfortunately I still don't have the reputation to reply on answers).
If you're struggling around the problem how to specifiy the relative path from within your controller's context, this might help you:
So if you have following folder you want to read/write files from/into"..
/myproject/web-app/temp/
you can access the file like this:
import org.codehaus.groovy.grails.commons.ApplicationHolder as AH
// getResource references to the web-app folder as root folder
Resource resource = AH.getApplication().getParentContext().getResource("/temp/myfile.txt)

Related

How to store multiple pdf file into public folder using laravel 8 in controller?

This my data that I want to store my pdf files in my public folders. Anyone can give me any idea?
I tried to foreach the data to get that file but it seems not working in my end. Anyone can help me?
To store files in your public folder you can use the public disk that's included in your application's filesystems configuration file, the default config will store files in storage/app/public.
To make these files accessible from the web though (which I'm assuming is what you want) you need to create a symbolic link from public/storage to storage/app/public.
To do that just run:
php artisan storage:link
Once you've done this you can use Laravel's storage facade to interact with the files in your public folder to save, retrieve and download them.
Store
use Illuminate\Support\Facades\Storage;
Storage::put('file.jpg', $contents);
Download
return Storage::download('file.jpg');
return Storage::download('file.jpg', $name, $headers);
Retrieve
$contents = Storage::get('file.jpg');
If you need to store user uploaded files to your public storage, you can do it like this:
$path = $request->file('yourUploadedPdf')->store('yourPdfsFolder');
Laravel's store method will generate a unique ID for the filename and the extension will be determined by the MIME type of the uploaded file. The store method also returns the path, including the generated filename, so you can store it in your DB if needed.
If you need to specify the filename then you can do this:
$path = $request->file('pdf')->storeAs(
'yourPdfsFolder', 'yourPdfFileName'
);
Just a note, I'm assuming you'll be having public as your default disk, if not, then you'll need to specify the disk you're using in these method / Storage facade calls.
And a further note, when using the public disk, everything - by default - gets stored under storage/app/public so anytime you're defining a folder to store your uploaded PDFs under, it'll be storage/app/public/yourFolder.

Drupal upload then move doesn't update path or filename in file list

I have a custom form using a "managed_file" which uploads to temp folder. Programmatically, I then load that file and move it to its permanent storage (overwriting any existing file with the* name) e.g.
// Upload file
$upfile = $this->entityTypeManager->getStorage('file')->load($fid);
// Source and destination
$sourceUri = $this->fileSystem->realpath($upfile->getFileUri());
$destinationUri = $this->fileSystem->realpath(\Drupal::config('system.file')->get('default_scheme') . "://") . '/x/y/z/XYZ_NEW.pdf';
// Move and overwrite
$this->fileSystem->move($sourceUri, $destinationUri, FileSystemInterface::EXISTS_REPLACE);
All of this works (i.e. the file physically is moved into the correct place with correct name); however, the file displayed in the listings (i.e. /admin/content/files) still shows the incorrect temporary folder as the URI.
Basically the file in the listings page seems to be showing the original filepath and name* of a previously successfully moved* file.
If I load this file with incorrect URI, i.e. using the incorrect temp path, the data loads, but then will not have a file info (as it doesn't exist. Also clicking the filename by browser under listings will show page not found and the URL showing the old URL i.e. /system/temporary?file=XYZ.pdf).
If I load this file by correct URI, i.e. using the correct destination path, file not found - same if I go to the path directly in the browser.
It appears the managed file doesn't know it was moved. How to resolve this bug?
The docs for FileSystem::move say "Moves a file to a new location without database changes or hook invocation."
So you are going to need to update the file entity with the new values..
Try this, untested:
// Upload file
$upfile = $this->entityTypeManager->getStorage('file')->load($fid);
// Source and destination
$sourceUri = $this->fileSystem->realpath($upfile->getFileUri());
$destinationUri = $this->fileSystem->realpath(\Drupal::config('system.file')->get('default_scheme') . "://") . '/x/y/z/XYZ_NEW.pdf';
// Move and overwrite
$newFileName = $this->fileSystem->move($sourceUri, $destinationUri, FileSystemInterface::EXISTS_REPLACE);
// Set the new file path on the file entity.
$upfile->setFileUri($newFileName);
// Set the file to permanent if needed.
$upfile->setPermanent();
// Save entity with changes.
$upfile->save();
I did not test this though.
You can check the functions on the file entity in the docs here
It turns out the class based methods do not update the database
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21File%21FileSystem.php/function/FileSystem%3A%3Amove/8.9.x
The procedural version does
https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file_move/8.9.x

Can Hive in Flutter Store BigData(some GB files)

I was thinking if I store a video or a movie and open that box will that video will be stored in my RAM or else it just load from ROM. I am a bit confused: Can anyone explain this to me?
I think you have misunderstood the concept of Database.
Any Database solution is to only store pure informational organized data. Not to store large files such as media, documents, or images.
On the contrary, storage need not be organized, all files can exist in one folder.
So, any database solution you use, always store Data Types.
In this case you can have a Data Model, which is also an essential thing in using a Database.
#HiveType(typeId: 0)
class Movie extends HiveObject {
#HiveField(0)
String name;
#HiveField(1)
int path;
}
Since Hive supports Dart objects, you don't have to convert toJson or any such for string the Data.
So when you have the file fetched from Storag, you can get the path using path_provider or from the File itself, and then Create a Object
File file = await // get the movie file using any means
final path = file.path
var box = await Hive.openBox('Movies');
var m = Movie()
..name = 'Batman Begins'
..path = path ;
box.add(m);
m.save();
Hope this clears your doubt.
Copy/save your video/media files in the Local File Storage and save file path in Hive Box.
Whenever you need get path from hive then get the file from local storage using that path.

Update an XML file in Google Drive via Google API

Let's say I have this minimal XML file on Google Drive.
<?xml version="1.0" encoding="UTF-8"?>
<MyCounter>
<counter>137</counter>
</MyCounter>
Using Google Script, I want to:
parse the XML
add 1 to the counter
update the file.
I'm at step 2 at the moment. I can delete the old file and create a new one with the same name and updated content. I prefer to update the existing one instead, so it will maintain the unique ID, and I can access the file with said ID instead of searching for it via file name.
You want to update a text file in your Google Drive without changing the file ID.
You want to add 1 to 137 of <counter>137</counter> in the file.
You want to achieve above using Google Apps Script.
If my understanding is correct, how about this sample script? I think that there are several answers for your situation. So please think of this as just one of them.
Flow:
Retrieve data from the text file.
Add 1 to number of <counter>{number}</counter> using replace().
Update the file using setContent().
By this flow, the file can be updated without changing file ID.
Sample script:
var fileId = "#####"; // Please set fileId here.
var file = DriveApp.getFileById(fileId);
var str = file.getBlob().getDataAsString();
var r = str.replace(/<counter>(\d+)<\/counter>/, function(_, p) {
return "<counter>" + (Number(p) + 1) + "</counter>";
});
file.setContent(r);
Note:
If you have already prepared the script for adding the counter, please use it.
References:
replace()
setContent()

The file download folder view in Struts 2

I'm creating a project of a school. I want to show the uploaded stuff by teachers to students.
But I also need to save the file in the folder which is named as faculty name. Student will be able to browse the main directory and after that he can go in the particular faculties folder.
How can I do it? Any suggestions will be appreciated.
For file upload I would start with example like in this answer. Moving files from temporary folder could be easily done by the file uploading action.
For browsing files in your case I would create an action that is able to navigate to the folder where the files are and get a list of files from that folder. Something like this
String file = application.getRealPath("/upload");
File f = new File(file);
String [] fileNames = f.list();
File [] fileObjects= f.listFiles();
for (int i = 0; i < fileObjects.length; i++) {
if(!fileObjects[i].isDirectory()){
String fname = file+fileNames[i];
out.println(fileNames[i]);
}
}
Then map this files to the JSP as links. When that link is clicked you can retrieve the actual path on the server when action is executed. What to do with the data, of course you can return stream result from the action that is used for streaming to the client browser. You can use docs examples from the Struts site or like in this example.
To navigate to the folder use parameters in GET request, that will be used to store current directory in session. You can change it if a user change the current directory from the view layer.

Resources