1

I have got this WebService that allows uploading/downloading any docs (mostly .docx, .doc, .pdf) and all it returns is byte[] when querying for downloading.

I have written this code

 string ContractGUID = dtContract.Rows[0]["ContractGUID"].ToString();

 //Get Bytes from WebService
 byte[] fileData = BLL.Contract.GetDocument(new Guid(ContractGUID));
 Response.Clear();
 Response.BinaryWrite(fileData);
 Response.AddHeader("Content-Disposition", "Attachment");
 Response.Flush();

The other methods that the WebService exposed are GetDocumentName and GetDocumentLen

Is it possible to determine the Mime-Type or force the browser to download it in the right format? Currently it is downloading as .htm in Chrome and when open, I see funny characters. Any better advice?

Thanks.

codingbiz
  • 26,179
  • 8
  • 59
  • 96
  • possible duplicate of [Using .NET, how can you find the mime type of a file based on the file signature not the extension](http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature) – Ta01 Sep 05 '12 at 13:54

2 Answers2

1

I think, the browser does it through filename.

e.g.:

response.Clear();
response.AddHeader("Content-Disposition", "attachment; filename=" + dbFile.filename.Replace(" ", "_"));
response.AddHeader("Content-Length", dbFile.data.Length.ToString());
response.ContentType = "application/octet-stream";
response.OutputStream.Write(dbFile.data, 0, dbFile.data.Length);
response.End();

dbFile.filename is a string

dbFile.data is a byte[]

kapsiR
  • 2,720
  • 28
  • 36
1

No, it's not possible to force the browser to download in the right format without you telling it via the Content-Type header.

Response.ContentType = "application/pdf"; //or whatever appropriate

If the web service exposes a GetDocumentName() method you can probably infer the appropriate format by looking at the name, assuming the name has a file extension. This, obviously, is not bullet proof since you can change the extension of a file to anything you want.

Another alternative would be to try and guess the file format by peeking at the first bytes. For example, if the first 4 bytes of the file are 25 50 44 46 then it's very likely that this is a PDF file. On this website, they have a pretty extensive list.

Here's the list of possible content-type headers.

Icarus
  • 63,293
  • 14
  • 100
  • 115