2

How to receive angular $http post multipart form data from Grails. Here I have sent multipart form data from Angular controller to the Grails. I am new to Grails.

Anyone can give me guidance to retrieve-boundary data. I don't Know exactly it's correct form to receive image file data with some input data also.

Request headers in browser's network console:

Provisional headers are shown
Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----    
WebKitFormBoundary0p6R8BecvYqzcbMK
Origin:file://
User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us)        
AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465     Safari/9537.53
Request Payload
------WebKitFormBoundary0p6R8BecvYqzcbMK
Content-Disposition: form-data; name="rackImage"; filename="PhoneGap.png"
Content-Type: image/png


------WebKitFormBoundary0p6R8BecvYqzcbMK
Content-Disposition: form-data; name="storeNo"

HD1304

------WebKitFormBoundary0p6R8BecvYqzcbMK
Content-Disposition: form-data; name="rackQty"

12
------WebKitFormBoundary0p6R8BecvYqzcbMK--
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
uday s
  • 291
  • 1
  • 2
  • 15
  • It sounds like you are trying to retrieve data, but you are using a POST request? That isn't the restful way. Typically HTTP GET is used for getting data from a server, and POST is used for sending data to a server. – James Nov 19 '15 at 17:22
  • What does your `$http.post` look like? What have you tried so far in your controller action? – tylerwal Nov 19 '15 at 18:12

1 Answers1

1

Here you go. Just write the following in your controller:

class MyController {

    def upload() {
        def multipartFile = params.rackImage

        InputStream is
        FileOutputStream fos

        byte[] fileRead = new byte[1024]
        File tempFile

        try {
            is = multipartFile.getInputStream()
            String fileName = multipartFile.getOriginalFilename()

            String path = "./"

            fileName = fileName.replaceAll("[^a-zA-Z0-9//._-]+", "").toLowerCase()

            tempFile = new File(path + "" + fileName)
            fos = new FileOutputStream(tempFile);
            int i = is.read(fileRead)
            while (i != -1) {
                fos.write(fileRead, 0, i);
                i = is.read(fileRead);
            }
        } catch (FileNotFoundException e) {
            log.error "Exception uploading", e
        } catch (IOException e) {
            log.error "Exception uploading", e
        } finally {
            fos?.close()
            is?.close()
        }

        // Now access the File: "tempFile"
    }
}
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121