Forum OpenACS Development: Re: how to import image via url?

Collapse
Posted by Torben Brosten on

ns_http works for text in aolserver 4.0.10, but not images. ns_httpget does appear to get the image contents, but this code does not display it, still (at least for safari and firefox), but does see okay when I send an http test request via telnet 80.

ad_page_contract {
    @ test
} {
    { url "http://kappacorp.com/fwgoofiness.jpg" }
}
set mime_type "image/jpeg"
set status 200
set nsd_version [ns_info version]
if { $nsd_version < 4.5 } {
    # pre aolserver 4.5 technique                                                                                                                                                          
    if {[catch {set page [ns_httpget $url]} err ]} {
        set page $err
        set mime_type "text/plain"
    } else {
        set page_sample [string range $page 0 20]
        ns_log Notice "get-image.tcl nsd_version: $nsd_version , url: $url , page_sample $page_sample"
    }

} else {

    if {[catch {set get_id [ns_http queue GET $url]} err ]} {
        set page $err
        set mime_type "text/plain"
    } else {
        set status [ns_http wait $get_id page]
        set page_sample [string range $page 0 20]
        ns_log Notice "get-image.tcl nsd_version: $nsd_version , status $status , url: $url , page_sample: $page_sample"
    }

}
ns_return $status $mime_type $page

Any suggestions on getting the display part to work?

Collapse
Posted by Gustaf Neumann on
Torben,

here is a short version based on the relatively new xotcl-core class ::xo::HttpRequest (cvs head)

ad_page_contract {
    @ test
} {
    { url "http://kappacorp.com/fwgoofiness.jpg" }
}

set r [::xo::HttpRequest new -url $url]
ns_headers connid [$r set status_code] [$r set content_type] [$r set content_length]
ns_write [$r set data]

Note that this version does not require you to write into the file system. Most probably, you can do similar with ns_http*.

-gustaf neumann
Collapse
Posted by Tom Jackson on

In AOLserver 4.5, the following works for me:

set id [ns_http queue http://192.168.1.102:8000/sns-thumb.jpg]

set ok [ns_http wait -result image -status status $id]

if {"$status" == "200"} {
    set fd [open [file join [file dirname [info script]] myimage.jpg] w+]
} else {
    ns_return $status text/html $image
    return -code return
}

# Very important:
fconfigure $fd -translation binary

puts $fd $image
close $fd

ns_return $status text/html "Status: $status <br>
<la href=\"/myimage.jpg\">My Image</a>"

ns_http queue and ns_http wait can be in different threads.