n92
n92

Reputation: 7592

How to convert String to File in Java and vice versa?

Converting String to File: I am passing a file to an action in controller

redirect(action:"downloadFile", params:[file:temp_file])

But when I do

def file = params.file
file.getName();

It give me error cannot cast object 'java.lang.String' to 'java.io.File'

How to convert String to File?

Upvotes: 1

Views: 11437

Answers (1)

Igor Artamonov
Igor Artamonov

Reputation: 35961

If your params.file is a file that user're uploading, you have to use following:

def file = request.getFile('file')
//where 'file' is a name of parameter, from <input type='file'/>

please read more about file upload in Grails

If you're trying to send this file to user's browser then:

String filename = '/reports/pdfreport9090.pdf'
response.contentType = "application/pdf"
response.setHeader("Content-disposition", "filename=$filename") 
File f = new File(filename)
response.outputStream << f.newInputStream()
response.outputStream.flush()

Upvotes: 2

Related Questions