下载的xlsx文件损坏使用IIS和c# httpwebrequest

xsuvu9jc  于 2023-02-08  发布在  C#
关注(0)|答案(1)|浏览(163)

我有以下问题:当我下载xlsx或docx文件时,下载的文件损坏。其他类型的文件(例如PDF)工作正常。我还测试了不同的MIME类型(应用程序/vnd. ms-excel或应用程序/vnd. openxmlformats-officedocument. spreadsheetml. sheet或应用程序/octet-stream)。

protected void btnActionDocAnsehen_Click(object sender, CommandEventArgs e)
{
    string connectionString = ConfigurationManager.ConnectionStrings["dataConnection"].ToString();
    SqlConnection conn = new SqlConnection(connectionString);

    conn.Open();

    //New Code for Downloading file
    string filepath = pfad;
    #endregion

    #region [Datenabruf mit WebDAV]
    //Create a stream for the file
    Stream stream = null;
    //This controls how many bytes to read at a time and send to the client
    int bytesToRead = 10000;
    // Buffer to read bytes in chunk size specified above
    byte[] buffer = new Byte[bytesToRead];

    try
    {
        // --------------- COPY REQUEST --------------- //

        // Create an HTTP request for the URL.
        HttpWebRequest httpCopyRequest =
          (HttpWebRequest)WebRequest.Create(filepath);

        httpCopyRequest.Timeout = 3000;

        // Pre-authenticate the request.
        httpCopyRequest.PreAuthenticate = true;

        //Create a response for this request
        HttpWebResponse httpCopyResponse = (HttpWebResponse)httpCopyRequest.GetResponse();

        if (httpCopyRequest.ContentLength > 0)
            httpCopyResponse.ContentLength = httpCopyRequest.ContentLength;

        //Get the Stream returned from the response
        stream = httpCopyResponse.GetResponseStream();

        // prepare the response to the client. resp is the client Response
        var resp = HttpContext.Current.Response;

        //Indicate the type of data being sent
        resp.ContentType = ReturnFiletype(Path.GetExtension(filepath));

        //Name the file 
        resp.AddHeader("Content-Disposition", "attachment; filename=\"" + pfad + "\"");

        int length;
        do
        {
            // Verify that the client is connected.
            if (resp.IsClientConnected)
            {
                // Read data into the buffer.
                length = stream.Read(buffer, 0, bytesToRead);

                // and write it out to the response's output stream
                resp.OutputStream.Write(buffer, 0, length);

                // Flush the data
                resp.Flush();

                //Clear the buffer
                buffer = new Byte[bytesToRead];
            }
            else
            {
                // cancel the download if client has disconnected
                length = -1;
            }
        } while (length > 0); //Repeat until no data is read
    }
    catch (WebException ex)
    {
        string message = "Die Datei konnte auf dem Server nicht gefunden werden! Bitte kontaktieren Sie die Administration!";
        //string message = filepath;
        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
    }
    finally
    {
        if (stream != null)
        {
            //Close the input stream
            stream.Close();
        }
    }
    #endregion
}
pnwntuvh

pnwntuvh1#

如果你不结束你的HttpContext.Current.Response,它会将页面添加到(文件)OutputStream的底部。
用文本编辑器(记事本)检查你的文件,你可能会在底部看到这样的东西:

<!DOCTYPE html>

<html lang="en">
<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>
(...)

我猜它与pdf的工作,因为可能你的PdfReader忽略任何不正确的格式,或一些标签后。
只需在循环后添加resp.End(),如下所示

(...)
} while (length > 0); //Repeat until no data is read

resp.End();

相关问题