2

I'm trying to put a file .xlsx to download. I'm using library.cs. When I used MVC 3, I do it with it:

HttpContext.Response.Clear();
HttpContext.Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(pck.GetAsByteArray(), "application/octet-stream");

But now, with .cs i don't know how I do it.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Developer123
  • 103
  • 1
  • 3
  • 12
  • 2
    I think this is more appropriate, given the OP has a `byte[]` rather than a stored file: [Response.WriteFile -- Write out a byte stream](http://stackoverflow.com/questions/3763256/response-writefile-write-out-a-byte-stream) – CodingIntrigue Jan 16 '14 at 13:14

1 Answers1

3

Try this:

public void DownloadExcel(byte[] buffer, string nameFile) {

    // Verify invalid chars on nameArchive parameter:
    var preparedName = new String(
       nameFile.Where(c => !Path.GetInvalidFileNameChars().Contains(c)).ToArray()
    );

    if (String.IsNullOrEmpty(preparedName))
       preparedName = "DefaultName";

    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.ContentType = 
       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    response.AddHeader("Content-Disposition", 
       String.Format("attachment;filename={0}.xlsx", preparedName));
    response.AddHeader("Content-Length", buffer.Length.ToString());
    response.BinaryWrite(buffer);
    response.End();
}

I think the problem in your case is the Mine Type, try using the same I used for the above method.

falvojr
  • 3,060
  • 4
  • 31
  • 54
  • 1
    I think you're right with the content type the first time - vnd.ms-excel is for .xls not .xlsx. You're not escaping `nameArchive` in case it contains non-ASCII though, but that's probably OK if it's under the application's control. – Rup Jan 16 '14 at 13:57
  • Thanks @Rup, I improved my answer based on your comment! – falvojr Jan 16 '14 at 14:11