How to make directory public on Grails?
my Grails app generates files 开发者_JAVA百科in a folder (e.g. "output"). How can I make that folder public, in order to expose the output files through URLs like:
http://localhost:8080/MyGrailsApp/output/myOutputFile1.xml
http://localhost:8080/MyGrailsApp/output/myOutputFile2.xml
Cheers!
Two ways you could do this. First is read the documentation for whatever your application server is and enable directory listing on whatever directory your xml files are stored in. If you need to be application server agnostic the second option could be to create a simple controller that uses URL mapping to automatically load and return the requested file. For documentation and examples of URL mapping in grails see http://www.grails.org/URL+mapping
This code is not perfect or tested, just typed it in here, but it should get you headed in the right direction
create a controller called OutputController.groovy
def viewFile = {
// add checks to ensure fileName parameter has no "/" or ".." to
// prevent directory transversal
def file = new File(OUTPUT_FILE_PATH + params?.fileName)
if (file.exists()) {
render(text: file.newInputStream().text, contentType: "text/plain",
encoding: "UTF-8")
} else {
render "FILE NOT FOUND: ${params?.fileName}"
}
}
update url mappings file
mappings {
"/output/$fileName?" {
controller = "output"
action = "viewFile"
}
}
精彩评论