如何从Grails中的上传文件中获取字节(byte [])

Ant*_*t's 7 grails groovy file-upload

我有一个像这样的上传表单(form.gsp):

<html>
<head>
    <title>Upload Image</title>
    <meta name="layout" content="main" />
</head>
    <body>  
        <g:uploadForm action ="upload">
            Photo: <input name="photos" type="file" />
            <g:submitButton name="upload" value="Upload" />
        </g:uploadForm>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我希望用户上传任何图片,当他点击upload按钮时,我需要一些方法来获取控制器操作中的图像并将其传递给视图:

def upload = { 
        byte[] photo = params.photos
            //other code goes here . . . .
    }
Run Code Online (Sandbox Code Playgroud)

这会引发错误:

Cannot cast object 'org.springframework.web.multipart.commons.CommonsMultipartFile@1b40272' with class 'org.springframework.web.multipart.commons.CommonsMultipartFile' to class 'byte'
Run Code Online (Sandbox Code Playgroud)

请注意,我不希望这些照片保存在我的数据库中.实际上,一旦upload动作完成,我将处理该图像并在upload视图中显示输出.如果我有解决方案,那将会很好.

提前致谢.

Jan*_*olm 11

def reqFile = request.getFile("photos")
InputStream file = reqFile.inputStream
byte[] bytes = file.bytes
Run Code Online (Sandbox Code Playgroud)

编辑:按建议将getBytes更改为字节,这是一种更好的groovy方式:)

  • +1,最后一行可以是`byte [] bytes = file.bytes` (2认同)

Rob*_*ska 9

如果要上传文件而不是存储它,并<img>在下一个请求中的另一个视图中显示该文件,您可以暂时将其存储在会话中:

grails-app/controllers/UploadController.groovy:

def upload = {
    def file = request.getFile('file')

    session.file = [
        bytes: file.inputStream.bytes,
        contentType: file.contentType
    ]

    redirect action: 'elsewhere'
}

def elsewhere = { }

def image = {
    if (!session.file) {
        response.sendError(404)
        return
    }

    def file = session.file
    session.removeAttribute 'file'

    response.setHeader('Cache-Control', 'no-cache')
    response.contentType = file.contentType
    response.outputStream << file.bytes
    response.outputStream.flush()

}
Run Code Online (Sandbox Code Playgroud)

grails-app/views/upload/form.gsp:

<g:uploadForm action="upload">
  <input type="file" name="file"/>
  <g:submitButton name="Upload"/>
</g:uploadForm>
Run Code Online (Sandbox Code Playgroud)

grails-app/views/upload/elsewhere.gsp:

<img src="${createLink(controller: 'upload', action: 'image')}"/>
Run Code Online (Sandbox Code Playgroud)

该文件可用于单个请求(因为我们在显示时将其删除).您可能需要针对错误情况实施一些额外的会话清理.

你可以很容易地调整它来保存多个文件(如果你试图上传一堆照片上传),但请记住每个文件占用内存.

使用会话的另一种方法是使用文件将文件传输到磁盘上的临时位置,MultipartFile#transferTo(File)然后从那里显示它们.


fix*_*ain 5

byte[] photo=request.getFile("photos").bytes
Run Code Online (Sandbox Code Playgroud)

如果你想作为一个图像返回:

response.contentType="image/png" //or whatever the format is...
response.outputStream << photo
Run Code Online (Sandbox Code Playgroud)