Download an Excel file

后端 未结 3 1299
猫巷女王i
猫巷女王i 2021-01-29 01:30

I have read some past posts here on how to download a Excel file from a website. So, I have setup the below code:

string path = MapPath(fname);
string name = Pa         


        
相关标签:
3条回答
  • 2021-01-29 01:35

    According to this link, you need to add this line:

    strFileName = Path.GetFileName(path);
    Response.TransmitFile( Server.MapPath(strFileName) );
    

    This will cause a Open / Save As dialog box to pop up with the filename of SailBig.jpg as the default filename preset.

    This of course assumes you're feeding a file that already exists. If you need to feed dynamically generated - say an image [or any file] that was generated in memory - you can use Response.BinaryWrite() to stream a byte array or write the output directly in Response.OutputStream.

    EDIT:

    Microsoft's MSDN site has a detailed explanation about File Downloading. It includes both samples for Java and .Net applications, the concept is the same:

    1. Get the response.
    2. With the response:
      1. Set the content type to "APPLICATION/OCTET-STREAM" (it means there's no application to open the file).
      2. Set the header to "Content-Disposition", "attachment; filename=\"" + + "\"".
      3. Write the file content into the response.
    3. Close the response.

    So, looking at the MSDN ASP.Net file download, you're lacking the 2.3 step. You're just writing the file name to the response.

    // transfer the file byte-by-byte to the response object
    System.IO.FileInfo fileToDownload = new
        System.IO.FileInfo("C:\\downloadJSP\\DownloadConv\\myFile.txt");
    Response.Flush();
    Response.WriteFile(fileToDownload.FullName);
    

    With this example you will download your file successfully, of course if you can get the file with no problems :).

    EDIT 2:

    The HTML component used to download any file must be a regular HTML Request. Any ajax request to download a file won't work. Microsoft explains that here. And the main quote:

    Its impossible to attach an event before and after a download through javascript. Browser doesn't allow this type of events for security reasons.

    0 讨论(0)
  • 2021-01-29 01:36

    Try adding such HTTP headers

    Content-Type: application/force-download
    Content-Type: application/vnd.ms-excel
    Content-Type: application/download
    
    0 讨论(0)
  • 2021-01-29 01:48

    You need to send this before the file attachment header:

    Response.ContentType = "application/vnd.ms-excel"
    

    See: Export data to excel file from Classic ASP failing

    0 讨论(0)
提交回复
热议问题