views:

1670

answers:

3

In C# i am doing

            context.Response.ContentType = "image/png";
            context.RewritePath(sz);
            context.Response.ContentType = "image/png";

It seems to redirect the path as i can see see images on my pages. However in firefox when i right click and select "view image" i get a download. Using this c++ code i can see the mime being application/octet-stream

#include <curl/curl.h> 
#include <ios>
#include <iostream>
#include <string>
#pragma comment(lib, "curllib")
using namespace std;
size_t function( void *ptr, size_t size, size_t nmemb, void *stream)
{
    cout << (char*)ptr;
    return size*nmemb;
}
size_t function2( void *ptr, size_t size, size_t nmemb, void *stream)
{
    return size*nmemb;
}
int main()
{
    CURL *c = curl_easy_init();
    curl_easy_setopt(c, CURLOPT_HEADERFUNCTION, function);
    curl_easy_setopt(c, CURLOPT_WRITEHEADER , 1);
    curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, function2);
    curl_easy_setopt(c, CURLOPT_WRITEDATA, 0);
    curl_easy_setopt(c, CURLOPT_URL, "http://localhost:3288/s/main/4/AAA.png");
    curl_easy_perform(c);
    curl_easy_cleanup(c);
    return 0;
}

My question is how do i set the mime to the correct type? Above i hardcode it to png which doesnt work. However i rather not hardcode any mime and have it work. I was able to redirect an XML file to somefile.aspx and have that the page set the content type and generate the XML. However rewriting to the image path seems to let the image work i just dont get the correct type.

How do i correct the content/mime type? As plan B i'll rewrite to a aspx file. Whats the best way to send an image? Could i do something like context.Response.OutputStream=stream("filename"); ?

A: 

Check out: http://stackoverflow.com/questions/887985/create-png-image-with-c-httphandler-webservice/888039

It should give you an example of dumping a PNG into the response.

Lloyd
+2  A: 

When you use RewritePath, whatever you have written to the head is discarded. Whatever is handling the new path is providing the header.

If you want to specify the content type, you can't use RewritePath. Instead you can use Response.BinaryWrite or Response.WriteFile to output the file data to the response stream after setting the header.

Guffa
A: 

application/octet-stream will tell your browser that the file is binary and your browser will then download it.

This has worked for me in the past (in an HttpHandler solely responsible for serving files, hence the clear calls):

Response.Clear();
Response.ClearHeaders();
Response.ContentType = "image/png";
Response.AddHeader("Content-Type", image/png");

If you do want to download the file, you can also add:

Response.AddHeader("Content-Disposition", "attachment; filename=myimage.png");

to suggest a filename to the browser to save as.

adrianbanks