I have a few PDF files in the assets folder of a Grails 3 application. I want to load them when the user clicks some button. i.e User clicks button "Get first book", and a grails controller looks for all files in the assets folder until it finds a match, and then returns the correct one.
Currently, I am loading the files by directly accessing the path. i.e. I am using an explicit aboslute path. According to this post, this is one of the advisable approaches. However, I want to load a file in grails by asking my application to get all assets in the asset folder, instead of using any paths.
My question then is, is it possible to get all files from the assets folder in a simple manner like we can get properties in the yml file (grailsApplication.config.someProperty)
Found the solution here: Grails : getting assets local storage path inside the controller
The following sample:
def assetResourceLocator
assetResourceLocator.findAssetForURI('file.jpg')?.getInputStream()?.bytes
worked fine for me.
this code makes something similar for me (however, my files are located outside of my project directory). Its a controller method, that receives the file name (id) and the filetype (filetype) and looks in a predefined directory. I think you just have to adapt your "serverLocation" and "contentLocation".
To get a list of the files, which you can pass to the view:
List listOfNewsletters = []
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File f = new File(serverLocation);
if (f.exists()) {
f.eachFile() { File file ->
listOfNewsletters.push([
path: file.path,
filename: file.name,
filetype: "pdf"
])
}
}
To deliver the file:
def openNewsletter() {
if (params.id != null && params.filetype != null) {
String pdf = (String) params.id + "." + (String) params.filetype;
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File pdfFile =new File(serverLocation + pdf);
response.contentType = 'application/pdf' // or whatever content type your resources are
response.outputStream << pdfFile.getBytes()
response.outputStream.flush()
}
}
Related
I am uploading one file that is kind of multipart. I want this file to save with different name.
tried with renameTo method but did not work.
tried moveto but did not work
below is my code
here graphic is multipart file
String picName = graphic.getOriginalFilename();EN_LENGTH) + "." + graphic.getContentType();
Path dirLocation = Paths.get(dirPath);
String newName = CommonUtil.getToken(Constants.STANDRAD_TOKEN_LENGTH) + "." + graphic.getContentType();
try {
InputStream is = graphic.getInputStream();
Files.copy(is, dirLocation.resolve(picName), StandardCopyOption.REPLACE_EXISTING);
boolean a = new File(dirLocation+picName).renameTo(new File(dirLocation+newName));
for security reasons I want it to save with different name.
Solved the issue by correcting the filename. The file name which I was generating randomly was not correct. it had some slash etc.
I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}
I have Successfully created folder and uploaded file in Document and Media Library.
I am storing File Name in DB and based on that file name I want to fetch that specific file from Document Library. I am new to Liferay.
I am fetching all Files saved in Document & Media Library using this Code Snippet. But is there any way to directly fetch File using File Name.
Here is my Code Snippet
public void getAllDLFileLink(ThemeDisplay themeDisplay,String folderName){
try {
Folder folder =DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
List<DLFileEntry> dlFileEntries = DLFileEntryLocalServiceUtil.getFileEntries(themeDisplay.getScopeGroupId(), folder.getFolderId());
for (DLFileEntry file : dlFileEntries) {
String url = themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/documents/" + themeDisplay.getScopeGroupId() + "/" +
file.getFolderId() + "/" +file.getTitle() ;
System.out.println("DL Link=>"+url);
}
} catch (Exception e) {
e.printStackTrace();
}
}
As your code snippet already finds the URL for a DLFileEntry, I'm assuming that you want to get hold of the binary content. Check DLFileEntry.getContentStream().
If this assumption is wrong and you want to embed the image in the HTML output of your portlet, use the URL within an <img src="URL-HERE"/> tag
You can use DLFileEntryLocalServiceUtil.getFileEntry(long groupId, long folderId, java.lang.String title) to get file using file name / title, as following:
String fileName = "abc.jpg";
Folder folder = DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(),
DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.getFileEntry(
themeDisplay.getScopeGroupId(), folder.getFolderId(), fileName);
However, title is stored with extension, therefore, you will require to pass complete name of image / file.
This is probably a very basic question but I tried various options and it didn't work out and hence requesting help. I want to create a file inside a specified directory. If the file already exists, I want to append data to it. Below is what I tried:
var DirectoryName: String = "LogFiles"
var dir: File = new File(DirectoryName);
dir.mkdir();
var ActorID: String = "1"
var FileName: String = DirectoryName + File.separator + "Actor_" + ActorID + ".log"
val FileObj: File = new File(FileName)
// FileObj.getParentFile().mkdirs();
// FileObj.createNewFile();
var FileWriterObj: FileWriter = null
var FileExistsFlag = 0
if (!FileObj.exists())
{
FileWriterObj = new FileWriter(FileObj.getName())
}
else
{
FileWriterObj = new FileWriter(FileObj.getName(), true)
FileExistsFlag = 1
}
var writer = new PrintWriter(FileWriterObj)
if(FileExistsFlag == 0)
writer.write("new file")
else
writer.append("appending to old file")
Internet search asks to use the below:
FileObj.getParentFile().mkdirs();
FileObj.createNewFile();
But it creates empty files inside the directory and creates new files outside the directory and appends to it. And also few posts suggests that there is no need to use createNewFile() to create a file.
I tried giving various path formats like below:
var DirectoryName: String = "../LogFiles"
var DirectoryName: String = "/home/ms/Desktop/Project/LogFiles"
But still it does not create the files inside the directory.
Can you please point me what I'm missing?
OS: Ubuntu 12.04
You should be using FileObj.getAbsolutePath, rather than FileObj.getName. getName just returns the name of the file, which explains why it was always being placed in the current directory.
The empty files issue could be solved by calling writer.close() at the end of your function. I don't think it's necessary to use createNewFile
I have tried to get this working and I have looked at many different resources online (as you can see from all of the comments I have made). I want to access a .pdf file that is either located in assets or res; It does not matter to which one so the easiest way will do.
I have the method below that will get the actual file and will call another method(under the first method below) with the Uri in the parameters.
Thank you very much for your help and I will be standing by to answer questions or add more content.
private void showDocument(File file)
{
//////////// ORIGINAL ////////////////////
//showDocument(Uri.fromFile(file));
//////////////////////////////////////////
// try 1
//File file = new File("file:///android_asset/RELATIVEPATH");
// try 2
//Resources resources = this.getResources();
// try 4
String PLACEHOLDER= "file:///android_asset/example.pdf";
File f = new File(PLACEHOLDER);
//File f = new File("android.resource://res/raw/slides1/example.pdf");
//getResources().openRawResource(R.raw.example);
// try 3
//Resources resources = this.getResources();
//showDocument(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(R.raw.example) + '/' + resources.getResourceTypeName(R.raw.example) + '/' + resources.getResourceEntryName(R.raw.example)));
showDocument(Uri.fromFile(f));
}
protected abstract void showDocument(Uri uri);
from link & Get URI of .mp3 file stored in res/raw folder in android
sing the resource id, the format is:
"android.resource://[package]/[res id]"
Uri path = Uri.parse("android.resource://com.androidbook.samplevideo/" + R.raw.myvideo);
or, using the resource subdirectory (type) and resource name (filename without extension), the format is:
"android.resource://[package]/[res type]/[res name]"
Uri path = Uri.parse("android.resource://com.androidbook.samplevideo/raw/myvideo");
If you do not know the ID of your resource, but just the name, you can use the getIdentifier(...) method of the Android Resouces object. You can retrieve the latter using the getResources() of your application context.
If, for example, your resource is stored in the /res/raw folder:
String rawFileName = "example" // your file name (e.g. "example.pdf") without the extension
//Retrieve the resource ID:
int resID = context.getResources().getIdentifier(rawFileName, "raw", context.getPackageName());
if ( resID == 0 ) { // the resource file does NOT exist!!
//Debug:
Log.d(TAG, rawFileName + " DOES NOT EXISTS! :(\n");
return;
}
//Read the resource:
InputStream inputStream = context.getResources().openRawResource(resID);
Very Helpful post.
Here's an alternative: Work with a FileDescriptor instead of the Uri, where possible.
Example: (In my case its a raw audio file)
FileDescriptor audioFileDescriptor = this.resources.openRawResourceFd(R.raw.example_audio_file).getFileDescriptor();
this.musicPlayer.setDataSource(backgroundMusicFileDescriptor);