I uploaded some documents into an uploadFolder C:/upload config path
environments {
development {
uploadFolder = "C:/upload/"
}
production {
uploadFolder = "C:/upload/"
}
test {
uploadFolder = "C:/Users/"
}
}
and I store it in the controller
documentInstance.fullPath = grailsApplication.config.uploadFolder + documentInstance.filename
How do I access the documents in the C:/upload/ file in Grails ?
There's no difference in how you access files in Grails then how you do it in a normal web application. If your paths are absolute paths you can do like this
def path = grailsApplication.config.uploadFolder + documentInstance.filename
File file = new File(path)
or to list all the documents in upload folder
Folder dir = new File(grailsApplication.config.uploadFolder)
dir.eachFile() {File file -> doSomething..}
Related
I have an asp.net web app which is published as an Azure cloud service.The application downloads the files from the server and saves it locally on the client machine.However,It does not seem to work when published as a cloud service.It works fine when published locally using IIS.
The code below is the where the file gets saved.
foreach (var item in userids)
{
//item.contractorpath= user filepath(client machine path eg, C:\test\)
string filePath =
Path.Combine(Server.MapPath("~/Content/Downloads"),
SessionInfo.CompanyId.ToString(), "Bill",
item.ContractorId.ToString());
if (Directory.Exists(filePath))
{
//System.IO.Directory.CreateDirectory(filePath);
DirectoryInfo di = new DirectoryInfo(filePath);
FileInfo[] TXTFiles = di.GetFiles("*.pdf");
if (TXTFiles.Length > 0)
{
foreach (FileInfo file in TXTFiles)
{
string fileName = file.Name;
if (!Directory.Exists(item.FolderPath))
{
System.IO.Directory.CreateDirectory(item.FolderPath);
}
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(Path.Combine(filePath, file.Name), Path.Combine(item.FolderPath, file.Name));
System.IO.File.Delete(Path.Combine(filePath, file.Name));
}
}
}
}
}
I have a Meteor application deployed with nginx.
I try to upload images from the application to save the images on the server. When I'm in localhost, I save my images in the myapp/public/uploads folder. But, when I deploy, this folder become myapp/bundle/programs/web.browser/app/uploads. So, when I upload an image, it saved in a new folder in myapp/public/uploads. But so, I can't access to it. When I'm in localhost I access to my images like that : localhost:3000/uploads/myImage.png but when I do myAdress/uploads/myImage.png I access to the myapp/bundle/programs/web.browser/app/uploads folder and not the one where the images are saved (myapp/public/uploads).
This is my code to save images :
Meteor.startup(function () {
UploadServer.init({
tmpDir: process.env.PWD + '/app/uploads',
uploadDir: process.env.PWD + '/app/uploads',
checkCreateDirectories: true,
uploadUrl: '/upload',
// *** For renaming files on server
getFileName: function(file, formData) {
//CurrentUserId is a variable passed from publications.js
var name = file.name;
name = name.replace(/\s/g, '');
return currentTileId + "_" + name;
},
finished: function(fileInfo, formFields) {
var name = fileInfo.name;
name = name.replace(/\s/g, '');
insertionImages(name, currentTileId, docId);
},
});
});
So, do you know how can I do to save and access to my images when the application is deployed ? Maybe save the image in the myapp/bundle/programs/web.browser/app/uploads folder or access to the myapp/public/uploads folder with an url.
This is what we do.
Use an external dir for uploads, say, /var/uploads. Keeping the uploads in public folder makes the meteor app to reload in the dev environment, on any file upload.
Now, at local, use Meteor to serve these files at a certain url. In production, use nginx to serve the same at the same url.
For Development
1) Symlink your upload dir to a hidden folder in public.
eg:
ln -s /var/uploads /path/to/public/.#static
2) Serve the public hidden folder via Meteor by using:
The url /static will server the folder public/.#static by using the following code on the server. Ref: How to prevent Meteor from watching files?
var fs = require('fs'), mime = require('mime');
WebApp.rawConnectHandlers.use(function(req, res, next) {
var data, filePath, re, type;
re = /^\/static\/(.*)$/.exec(req.url);
if (re !== null) {
filePath = process.env.PWD + '/public/.#static/' + re[1];
try {
stats = fs.lstatSync(filePath);
if (stats.isFile()) {
type = mime.lookup(filePath);
data = fs.readFileSync(filePath, data);
res.writeHead(200, {
'Content-Type': type
});
res.write(data);
res.end();
}
}
catch (e) {
// console.error(filePath, "not found", e); // eslint-disable-line no-console
next();
}
}
else {
next();
}
});
For production
1) Use nginx for serving the upload dir
server {
...
location /static/ {
root /var/uploads;
}
...
}
That's it. /static will server the content of your uploads dir i.e. /var/uploads
I would like to run different versions of my Grails (2.3.5) app at the same time in the same tomcat using different DBs.
At the moment I am having an external configuration file where I specify my DB configurations.
The filename is hardcoded:
<tomcat-home>/conf/sc.conf
"sc.war" is the name of my war-file. As I now want/need to run multiple versions I would like to make the name of the conf file variable.
<tomcat-home>/conf/<warfilename>.conf
Is there a way to get the war-file-name at runtime?
I am open for other ways to solve my problem. Thanks for your help.
You just need to give applicationBaseDir path into external config file
applicationBaseDir = ""
println "Bootstrapping application"
println ">>>>>>>>Environment >>>>>"+GrailsUtil.environment
Environment.executeForCurrentEnvironment {
development {
println "Keeping applicationBaseDir "+grailsApplication.config.applicationBaseDir+" as is."
}
production {
//Following code finds your project path and set applicationBaseDir
Process findPresentWorkingDirectory = "pwd".execute()
def pwd = findPresentWorkingDirectory.text
def pwdTokens = pwd.tokenize("/")
pwdTokens.pop()
applicationBaseDir = pwdTokens.join("/")
println ">>>> applicationBaseDir "+applicationBaseDir
applicationBaseDir = "/"+applicationBaseDir+"/webapps/applicationDir/"
println 'grailsApplication.config.applicationBaseDir '+applicationBaseDir
}
}
Or you directly set applicationBaseDir in external config file
applicationBaseDir = "/home/tomcat/webapps/applicationDir/"
Now, to refer specific external config file add into your project file Config.groovy file following code
environments {
development {
String codeSystemClassFilePath = AnyDomainClassNameFromYourApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath()
// Here AnyDomainClassNameFromYourApplication change to your application domain class name e.g.I have domain class Student then I replace it with Student
def arrayWithLastValueAsProjectName = codeSystemClassFilePath.split('/target/classes/')[0].split('/')
String projectName = arrayWithLastValueAsProjectName[arrayWithLastValueAsProjectName.size()-1]
println "App name in dev==>"+projectName
grails.logging.jul.usebridge = true
grails.config.locations = [
"file:${userHome}/grails/${projectName}.groovy"
]
grails.assets.storagePath = ""
}
production {
String codeSystemClassFilePath = AnyDomainClassNameFromYourApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath()
def arrayWithLastValueAsProjectName = codeSystemClassFilePath.split('/WEB-INF/classes/')[0].split('/')
String projectName = arrayWithLastValueAsProjectName[arrayWithLastValueAsProjectName.size()-1]
println "App name in production==>"+projectName
grails.logging.jul.usebridge = false
grails.config.locations = [
"file:${userHome}/grails/${projectName}.groovy"
]
}
}
//here grails/ is my default folder use to store exernal-config-files
I hope this helps you!
I am trying to read a string in from an external config file, but am for some reason only getting an empty object. Here is the config file (DirectoryConfig.groovy)
directory {
logDirectory = "c:\\opt\\tomcat\\logs\\"
}
And the code that retrieves the directory (from a controller):
String dirName = grailsApplication.config.directory.logDirectory
File directory = new File(dirName)
For some reason, dirName always ends up being "{}", and as a result the file cannot be read. What am I doing wrong here?
Creating DirectoryConfig.groovy in your grails-app/conf/ directory will not work by convention.
You should consider implementing solution that is recommended for externalizing Grails configuration - delivering .groovy or .properties files from classpath or filesystem. Take a look at commented code in Config.groovy:
// grails.config.locations = [ "classpath:${appName}-config.properties",
// "classpath:${appName}-config.groovy",
// "file:${userHome}/.grails/${appName}-config.properties",
// "file:${userHome}/.grails/${appName}-config.groovy"]
It's very common way to provide configuration files that depend on runtime property:
// if (System.properties["${appName}.config.location"]) {
// grails.config.locations << "file:" + System.properties["${appName}.config.location"]
// }
I often use something like this (it's part of the Config.groovy file):
grails.config.locations = []
grails.project.config.type = "classpath"
grails.project.config.extension = "groovy"
environments {
development {
grails.project.config.file = "development-config.${grails.project.config.extension}"
}
test {
grails.project.config.file = "test-config.${grails.project.config.extension}"
}
}
if (System.properties["grails.config.type"]) {
grails.project.config.type = System.properties["grails.config.type"]
}
if (System.properties["grails.config.file"]) {
grails.project.config.file = System.properties["grails.config.file"]
}
grails.config.locations << "${grails.project.config.type}:${grails.project.config.file}"
By default it assumes that there is e.g. development-config.groovy file in the classpath, but I can simply change it by setting -Dgrails.config.file=/etc/development.properties -Dgrails.config.type=file in Java runtime so it uses /etc/development.properties file instead of the default one.
If you would like to run your example in the simplest way, you will have to do:
1) put your DirectoryConfig.groovy in the classpath source e.g. src/java (attention: it wont work if you put your file in src/groovy)
2) define in your Config.groovy:
grails.config.locations = [
"classpath:DirectoryConfig.groovy"
]
3) re-run your application. grailsApplication.config.directory.logDirectory should now return the value you expect.
For more information about externalizing configuration go to http://grails.org/doc/latest/guide/conf.html#configExternalized
I'm implementing a file upload functionality to a web-app in Grails. This includes adapting existing code to allow multiple file extensions. In the code, I've implemented a boolean to verify that the file path exists, but I'm still getting a FileNotFoundException that /hubbub/images/testcommand/photo.gif (No such file or directory)
My upload code is
def rawUpload = {
def mpf = request.getFile("photo")
if (!mpf?.empty && mpf.size < 200*1024){
def type = mpf.contentType
String[] splitType = type.split("/")
boolean exists= new File("/hubbub/images/${params.userId}")
if (exists) {
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
} else {
tempFile = new File("/hubbub/images/${params.userId}").mkdir()
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
}
}
}
I'm getting the exception message at
if (exists) {
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
}
So, why is this error happening, as I'm simply collatating an valid existing path as well as a valid filename and extension?
Why do you think that convertation of File object to Boolean returns existence of a file?
Try
File dir = new File("/hubbub/images/${params.userId}")
if (!dir.exists()) {
assert dir.mkdirs()
}
mpf.transferTo(new File(dir, "picture.${splitType[1]}"))