簡體   English   中英

使用api下載.xlsx文件會返回XML格式的文件? VB.NET

[英]Download .xlsx file using an api returns XML formatted file? VB.NET

我正在嘗試使用API​​從Web應用程序下載.xlsx文件。 但是,文件的字符串內容始終是混亂的,並且似乎包含XML內容。 我假設它是XML,因為在第一行中提到了“ [Content_Types] .xml”。

響應頭提到返回的內容類型是“ application / octet-stream”。 我嘗試在請求標頭中添加content-type =“ application / vnd.openxmlformats-officedocument.spreadsheetml.sheet”,但該Web應用程序“無法識別”該操作。 所以我不能返回.xlsx類型的文件...

當我嘗試下載此文件並將其另存為.xlsx時,無法打開它,因為它始終表示文件已損壞。 但是,使用Postman下載文件不會損壞。 我不確定在下載和保存二進制64基編碼的數據時哪里出了問題。 請幫忙! 這是我正在使用的代碼,用於下載和保存文件。

If My.Computer.FileSystem.DirectoryExists(DownloadLocation) = False Then
        MsgBox("Folder path '" & DownloadLocation & "' does not exist.", MsgBoxStyle.Information)
        Return
    End If

    Dim url As String = 'I am setting the URL here, tested on postman and no issues here 

使用函數從響應頭獲取文件名,文件路徑和名稱沒有問題。

 Dim Filepath As String = DownloadLocation & "\" & filename.Split(".").First & "_" & Format(Now, "yyyymmdd hhmmss") & "." & filename.Split(".").Last

    Dim credentials As String = ""
    credentials = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(LoginName + ":" + PW))
    Dim Request As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
    With Request
        .Headers.Set(HttpRequestHeader.Authorization, credentials)
        .Headers.Set("X-Application-Key", My.Settings.APIKey)
        .Method = "GET"
        .AutomaticDecompression = DecompressionMethods.GZip
    End With

    Try
        Dim response As HttpWebResponse
        response = Request.GetResponse
        Dim stream As Stream = response.GetResponseStream
        Dim reader As New StreamReader(stream)
        Dim Ofile As FileStream = New FileStream(Filepath, FileMode.Create)
        Dim Owrite As StreamWriter = New StreamWriter(Ofile)
        Owrite.Write(reader.ReadToEnd)
        reader.Close()
        Owrite.Close()
        Ofile.Close()
    Catch ex As Exception
        MsgBox("Download failed..." & vbNewLine & vbNewLine & ex.ToString, MsgBoxStyle.Information)
        Return
    End Try

該文件另存為.xlsx文件,但是當我嘗試打開該文件時,Excel表示該文件已損壞。 有人知道這里發生了什么嗎?

刪除GZip減壓。 首先,您不需要它。 其次,這給您帶來了麻煩。

XLSX文件是一組壓縮成一個文件的XML文件。 並重命名為.xlsx擴展名。 提取任何xlsx文件,將其重命名以壓縮並解壓縮內容。 您將看到XML結構及其目錄。

AutomaticDecompression可以在響應流字節中正確檢測* ZIP,並在客戶端為您解壓縮。

GZipping不需要壓縮的內容,因為在大多數情況下,壓縮壓縮文件會使文件更大。 由於消息的熵已經最大化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM