2012-01-24 14 views
7

上傳的文件我有一個上傳表單像這樣(form.gsp)字節(字節[]):如何從Grails中

<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> 

我希望用戶上傳任何圖片,當他點擊在upload按鈕,我需要一些方法來得到我的控制器操作的圖像,並將其傳遞給視圖:

def upload = { 
     byte[] photo = params.photos 
      //other code goes here . . . . 
    } 

這將引發一個錯誤:

Cannot cast object '[email protected]b40272' with class 'org.springframework.web.multipart.commons.CommonsMultipartFile' to class 'byte' 

請注意,我不希望這些照片保存在我的數據庫中。實際上,一旦upload操作完成後,我將使用該圖像進行處理,並在upload視圖中顯示輸出。所以如果我有解決方案,這將是一件好事。

在此先感謝。

回答

8

如果您想要上傳文件,請不要存儲它,並在下一個請求的另一個視圖中將其顯示在<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() 

} 

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

<g:uploadForm action="upload"> 
    <input type="file" name="file"/> 
    <g:submitButton name="Upload"/> 
</g:uploadForm> 

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

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

該文件將可用於單個請求(因爲我們在顯示時將其刪除)。您可能需要爲錯誤情況實施一些額外的會話清理。

你可以很容易地適應這個來保存多個文件(如果你正在嘗試上傳一些照片上傳),但要記住每個文件都佔用內存。

使用會話的替代方法是使用MultipartFile#transferTo(File)將文件傳輸到磁盤上的臨時位置,並從那裏顯示它們。

+0

這看起來很棒,但是當我查看'anywhere.gsp'時,我無法看到任何圖像! –

+0

嗯,有趣。上面的代碼爲我工作,逐字。該頁面說什麼圖像的來源是什麼?也許你可以添加一些日誌來幫助調試它。 –

+0

對不起,它工作,我在控制器名稱中犯了一個錯字:謝謝你的東西:) –

9
def reqFile = request.getFile("photos") 
InputStream file = reqFile.inputStream 
byte[] bytes = file.bytes 

編輯:改變的getBytes以字節爲單位的建議和是一個更好的常規方式:)

+2

+1,最後一行可以是'byte [] bytes = file.bytes' –

+0

一切正常!但如果我想要顯示用戶在視圖中上傳的圖像,我該怎麼做? –

+0

你可以寫你的字節到response.outputStream –

5
byte[] photo=request.getFile("photos").bytes 

,如果你想返回爲圖像做:

response.contentType="image/png" //or whatever the format is... 
response.outputStream << photo