如何使用grails文件夹中的jQuery api获取数据?

时间:2014-08-29 13:29:05

标签: jquery grails

我有专辑课专辑和照片。在我的数据库中,相册具有:id,name和user_id以及照片:id,album_id,名称和类型。当用户登录grails创建名称为username的文件夹并在那里保存图片(在grails中的web-app文件夹中而不是数据库中)。现在我需要在我的网络应用程序中使用jQuery API获取这些图片。我的API控制器如下所示:

def getAlbumsList(){
    def resultJSON = [:]

    try{
        int userId

        try{
            userId = params.int('userId')
        }
        catch(Exception e){}

        def conn =  sessionFactory.currentSession.connection()
        def sql =  new Sql(conn)

        def albumList = sql.rows("SELECT ab.a_name, MAX(p.p_name) as p_name FROM album ab INNER JOIN photo p ON ab.id = p.album_id WHERE ab.user_id = ?", userId)
        sql.close()

        def albums = []
        for(album in albumList){
            albums << [albumName: album.a_name, lastPhoto: grailsApplication.mainContext.getResource("album/" + album?.p_name + ".jpg")?.file?.absolutePath]
        }

        resultJSON = [msg: 1, albums: albums]

    }
    catch(Exception e){
        resultJSON = [msg: 0, ex: e.getMessage() +  " " + e?.getCause() ]
    }

    render resultJSON as JSON
}


/*
 * Get photos for user.
 *
 * <p>
 * @param userId        id of user
 *
 * <p>
 * @return [msg: 1, photos: (Photo url data)] or [msg: 0, ex: Exception description ]
 *
 * <p>
 * @see Photo
 * @see User
 *
 */
def getAlbumPhotosList(){
    def resultJSON

    try{
        int userId

        try{
            userId = params.int('userId')
        }
        catch(Exception e){}

        def conn =  sessionFactory.currentSession.connection()
        def sql =  new Sql(conn)

        def photosList =  sql.rows("SELECT p.p_name FROM album ab INNER JOIN photo p ON ab.id = p.album_id WHERE ab.user_id = ?", userId)
        def photos = []
        for(photo in photosList){
            photos << grailsApplication.mainContext.getResource("album/" + photo?.p_name + ".jpg")?.file?.absolutePath
        }

        resultJSON = [msg: 1, photos: photos]
        sql.close()
    }
    catch(Exception e){
        resultJSON = [msg: 0, ex: e.getMessage() +  " " + e.getCause() ]
    }

    render resultJSON as JSON
}

}

我可以这样做吗? 谢谢你的回答,对不起我的英文

1 个答案:

答案 0 :(得分:1)

只需将文件名或网址存储在Photo类中,因为您永远不知道文件夹中的数据是什么