... and the handler itself:
private byte[] PngHandler(System.Collections.Specialized.NameValueCollection boundVariables,
ESRI.ArcGIS.SOESupport.JsonObject operationInput,
string outputFormat,
string requestProperties,
out string responseProperties)
{
responseProperties = "{\"Content-Type\" : \"image/png\"}";
System.IO.FileStream fs = new System.IO.FileStream("c:\\temp\\8540.png", System.IO.FileMode.Open);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
const int count = 1024;
while(true)
{
byte[] buf = br.ReadBytes(count);
ms.Write(buf, 0, buf.Length);
if (buf.Length < count)
break;
}
br.Close();
fs.Close();
fs.Dispose();
return ms.ToArray();
}
That was a real good template, but can be simplified and generalized in several ways:
- For reading a file in .net you can simply use File.ReadAllBytes(path);
- Determining the correct mime type is discussed here
- Setting the responseProperties is much easier when using the JsonObject
This results in two little functions, which do the job:
protected string GetMimeType(FileInfo fileInfo)
{
string mimeType = "application/unknown";
RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(fileInfo.Extension.ToLower());
if (regKey != null)
{
object contentType = regKey.GetValue("Content Type");
if (contentType != null)
mimeType = contentType.ToString();
}
return mimeType;
}
protected byte[] FileHandler(string path, out string responseProperties)
{
FileInfo f = new FileInfo(path);
string contentType = GetMimeType(f);
long contentLength = f.Length;
JsonObject props = new JsonObject();
props.AddString("Content-Type", contentType);
props.AddLong("Content-Length", contentLength);
props.AddString("Pragma", "public");
props.AddString("Cache-control", "must-revalidate");
props.AddString("Content-Disposition", "inline; filename=\"" + path + "\"");
responseProperties = props.ToJson();
return File.ReadAllBytes(path);
}