Grails controller: how render image from byte array

时光怂恿深爱的人放手 提交于 2019-12-12 02:22:38

问题


I have byte array byteImg but I want render in my controller jpeg from byte array:

    def getSelfie = new HTTPBuilder()
    getSelfie.request(fullSelfieUrl, GET, JSON) { req ->
        headers.'X-DreamFactory-Session-Token' = session_id
        headers.'X-DreamFactory-Application-Name' = 'checkReg'
        response.success = { resp, reader ->
            assert resp.statusLine.statusCode == 200
            println "Get response: ${resp.statusLine}"
            println "Content-Type: ${resp.headers.'Content-Type'}"
            resp = reader as grails.converters.JSON

            String str = resp.toString()
            JSONObject jsonObject = new JSONObject(str)
            selfieRend = jsonObject.getString("selfie")
            byteImg = selfieRend.getBytes()

            render byteImg
            return byteImg
        }
        response.'404' = {
            println 'Information not found'
        }
    }

how to do it? Thank you so much


回答1:


I haven't tested it but as per wiki this should work:

def getSelfie(){
  def http = new AsyncHTTPBuilder(
            poolSize : 4,
            uri : fullSelfieUrl,
            contentType : ContentType.JSON )

  def result = http.get() { resp, json -> json.selfie.bytes }

  while( !result.done ) Thread.sleep 1000

  def bytes = result.get()

  response.setHeader 'Content-disposition', "inline; filename=someName.jpg"
  response.setHeader 'Content-Type', 'image/jpg'
  response.outputStream.withStream{ it << bytes }
}


来源:https://stackoverflow.com/questions/34371245/grails-controller-how-render-image-from-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!