2011-05-24 32 views
6

Me'v utiliza this método para copiar un archivo a una carpeta en mi proyecto (primer método), y yo hemos editado por lo que el lugar se guarda en mi 'Localización' en las presentaciones de clase (véase más adelante).Griales descargar el archivo

Ahora quiero ser capaz, después de una imagen al hacer clic en mi punto de vista, descargar ese archivo. Cómo puedo hacer eso ?

class Submissions { 

    Date dateSub 
    String Location 
    String fileName 

} 

Respuesta

1

sólo hay que hacer que los bytes en la respuesta. Hacemos algo así como

def streamFile = { 
    // load the attachment by id passed on params 
    .... 
    response.contentType = attachment.contentType.toLowerCase() 
    response.contentLength = attachment.data.length() 
    // our 'data' field is a Blob, the important thing here is to get the bytes according to 
    // how you get the actual downlaod 
    response.outputStream.write(attachment.data.getBytes(1L, attachment.data?.length() as int)) 
} 

en nuestro controlador, y haga un enlace a ese método controlador en el SGP. Dependiendo de cómo vea el tipo de contenido, el navegador hará las cosas por usted. Si tiene un tipo de imagen, por ejemplo, mostrará la imagen. Si tiene un documento en Word, el navegador debe abrir el programa apropiado para el sistema del usuario.

+1

hm usted está hablando acerca de los bytes aquí .. Los archivos no se almacenan en la base de datos, solo su ubicación. ¿Lo estás tomando en cuenta, verdad? – Michael

+0

@michael si almacena la ruta en el archivo db, necesita obtener un objeto File y obtener los bytes. – hvgotcodes

20

he hecho algo similar a la siguiente:

Asumiendo que su página de descarga tiene la instancia correspondiente presentaciones ...

<g:link action="downloadFile" id="${aSubmission.id}"> 
    <img>...etc...</img> 
</g:link> 

Luego, en el controlador (es su "ubicación" de la ruta de acceso al archivo?):

def downloadFile = { 
    def sub = Submissions.get(params.id) 
    def file = new File("${sub.location}/${sub.fileName") 
    if (file.exists()) 
    { 
     response.setContentType("application/octet-stream") // or or image/JPEG or text/xml or whatever type the file is 
     response.setHeader("Content-disposition", "attachment;filename=\"${file.name}\"") 
     response.outputStream << file.bytes 
    } 
    else render "Error!" // appropriate error handling 
} 
+1

Funcionó, da error para file.exists ya que no hay tal método debe ser file.exists() – praveen2609

2

Bueno, siempre es mejor mantener la lógica de descarga envuelto dentro de un try/catch y también estableció WebRequest como falso. http://lalitagarw.blogspot.in/2014/03/grails-forcing-file-download.html

def downloadFile() { 
    InputStream contentStream 
    try { 
     def file = new File("<path>") 
     response.setHeader "Content-disposition", "attachment; filename=filename-with-extension" 
     response.setHeader("Content-Length", "file-size") 
     response.setContentType("file-mime-type") 
     contentStream = file.newInputStream() 
     response.outputStream << contentStream 
     webRequest.renderView = false 
    } finally { 
     IOUtils.closeQuietly(contentStream) 
    } 
}