0

I am trying to upload a file via REST using GRAILS

curl -X POST -H "Cache-Control: no-cache" -H "Postman-Token: d5d7aef8-3964-311b-8b64-4a7a82c52323" -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "file1=myfile.jpg" -F "fname=swateek" -F "lname=jena" 'http://localhost:8081/sampleFileREST/document/upload'

Here's how my controller looks like:

class DocumentController extends RestfulController<Document> {

static responseFormats = ['json', 'xml']

def upload() {

   def fileLocation="<xml>empty</xml>"
    def file = request.getParameter('file1')
    def  f1 = request.getParameter('fname')
    def f2 = "<abc>"+request.getParameter('lname')+"</abc>"
   def params = "gf"
    if(file.empty) {
        fileLocation = "<xml>"+"File cannot be empty"+"</xml><allprm>"+params+"</allprm>"
    } else {
        def documentInstance = new Document()
        documentInstance.filename = file.originalFilename
        documentInstance.fullPath = grailsApplication.config.uploadFolder + documentInstance.filename
        file.transferTo(new File(documentInstance.fullPath))
        documentInstance.save()
        fileLocation = "<xml>"+documentInstance.fullPath+"</xml>"
    }
   /* return "File uploaded to: "+documentInstance.fullPath */

    render(text: fileLocation, contentType: "text/xml", encoding: "UTF-8")
}

}

I am able to access the parameters of the request, anything except the file I am sending in the request.

Unable to figure out what's wrong here.

UPDATE

I had used .getParameter() to fetch a file. That's incorrect, the correct way is as below:

request.getFile('<filename>') // without the <>

This might raise an error in IntelliJ as "Symbol Not Found" or "Cannot Resolve Method", please follow the procedure in the answer below.

swateek
  • 6,735
  • 8
  • 34
  • 48

1 Answers1

0

Damn the IDE that I was using, IntelliJ.

Also, this piece of code while getting the file:

def file = request.getParameter('file1')

should be replaced as

def file = request.getFile('file1')

Now previously, when I was using the request.getFile() method I was getting an "Symbol Not Found" error and it was failing to execute the request.

Solution:

  • Open IntelliJ
  • Click on "File"
  • Find the option "Invalidate Caches/Restart" and wait for IntelliJ to come back again.

If this doesn't work, the other way is mentioned in this answer: IntelliJ IDEA JDK configuration on Mac OS

Community
  • 1
  • 1
swateek
  • 6,735
  • 8
  • 34
  • 48