Reputation: 134
I am very new to grails and starting learning by myself. I am trying to reproduce the example of document upload/download.
My Domain Class:
package demo2
class Document {
String filename
String type
String fullPath
Date uploadDate = new Date()
static constraints = {
filename(blank:false,nullable:false)
fullPath(blank:false,nullable:false)
}}
My DocumentController is:
package demo2
class DocumentController {
def list()
{
params.max = 10
[DocumentInstanceList:Document.list(params),
DocumentInstanceTotal: Document.count()]
}
def index (Integer max)
{
redirect (action: "list", params:params)
}
def upload() { // upload a file and save it in a the
file system defined inside the config file
def file = request.getFile('file')
if(file.empty) {
flash.message = "File cannot be empty"
} else {
def DocumentInstance = new Document()
DocumentInstance.filename = file.originalFilename
DocumentInstance.type = file.contentType
DocumentInstance.fullPath = grailsApplication.config.uploadFolder +file.originalFilename
file.transferTo(new File(DocumentInstance.fullPath))
DocumentInstance.save flush:true
}
redirect (action:'list')
}
def download(long id) { //download a file saved inside the file system
Document DocumentInstance = Document.get(id)
if ( DocumentInstance == null) {
flash.message = "Document not found."
redirect (action:'list')
} else {
response.setContentType("APPLICATION/OCTET-STREAM")
response.setHeader("Content-Disposition", "Attachment;Filename=\"${DocumentInstance.fileName}\"")
def file = new File(DocumentInstance.fullPath)
def fileInputStream = new FileInputStream(file)
def outputStream = response.getOutputStream()
byte[] buffer = new byte[4096];
int len;
while ((len = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.flush()
outputStream.close()
fileInputStream.close()
}
}
}
my list.gsp is
<g:link action="download" id="${DocumentInstance.id}"> ${fieldValue(bean: DocumentInstance, field: "fileName")}</g:link>
But when I run the app, I am getting the following error:
Error 500: Internal Server Error URI /demo2/document/list Class java.lang.NullPointerException Message Cannot get property 'id' on
null object
How do I rectify this error. Kindly help me.
Upvotes: 0
Views: 3440
Reputation: 1174
Your gsp should be
<g:each in="${DocumentInstanceList}" var="DocumentInstance">
<g:link action="download" id="${DocumentInstance.id}"> ${DocumentInstance.fileName}</g:link> <br/>
</g:each>
You want to iterate over the items in your list, not just print a single item. You're getting a NPE because there's currently no DocumentInstance
variable on the page (as the comment above says).
Upvotes: 1