[英]convert blob to Excel file and download, file cannot be open
我有一個 api,它返回下面的響應,其中包含 excel 文件內容。
所以現在我需要將它們轉換為 excel 文件並為用戶下載。
這是api函數
[HttpGet]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> DownloadLoadedTrnFile(string S3Path)
{
try
{
string bucket = "taurus-" + GetEnvironmentSettings() + "-trn";
string fileName = "";
string[] fileStr = S3Path.Split('-');
if (fileStr.Count() > 0)
{
fileName = fileStr.Last();
}
Stream responseStream = await _imageStore.GetImage(bucket, S3Path);
if (responseStream == null)
return NotFound();
using (MemoryStream ms = new MemoryStream())
{
responseStream.CopyTo(ms);
var finalResult = File(System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()), MimeTypesMap.GetMimeType(S3Path), fileName);
return Ok(finalResult);
}
}
catch (Exception ex)
{
return StatusCode(500, "Error in downloading file.");
}
}
public async Task<Stream> GetImage(string bucketName, string objectKey)
{
GetObjectRequest originalRequest = new GetObjectRequest
{
BucketName = bucketName,
Key = objectKey
};
try
{
GetObjectResponse response = await S3Client.GetObjectAsync(originalRequest);
// AWS HashStream doesn't support seeking so we need to copy it back to a MemoryStream
MemoryStream outputStream = new MemoryStream();
response.ResponseStream.CopyTo(outputStream);
outputStream.Position = 0;
return outputStream;
}
catch (AmazonS3Exception ex)
{
// Not found if we get an exception
return null;
}
}
我在前端有這樣的功能,如下所示,
function saveTextAsFile(data, filename, contentType) {
if (!data) {
console.error('Console.save: No data')
toastr.error("No data received from server");
return;
}
if (!filename) filename = 'noname.xlsx';
var blob = new Blob([s2ab(atob(data))], {
type: contentType
});
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
}
和功能
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
此功能在只有普通文本的 excel 中運行良好。 但是,我正在嘗試下載這個excel,它具有豐富的內容,例如彩色邊框、下拉菜單、多張表格。
當我嘗試使用相同的函數下載 excel 文件時,它拋出了這個錯誤:
為了幫助您更了解我的問題,這里是 API HTTP CAll
我嘗試在線搜索解決方案,但沒有運氣。 我實際上不明白這里有什么問題。 任何事情都會有所幫助謝謝。
感謝您的所有回復,並讓我稍微了解一下,最后我解決了這個問題。
好吧,發現它的問題是因為在 API 中我將它包裝在 UTF-8 中。 但是,它 (Excel) 不應包含在 UTF-8 中。 僅當我正在下載 csv 文件時。
var finalResult = File(System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()),
MimeTypesMap.GetMimeType(S3Path), fileName);
變成
var finalResult = File(ms.ToArray(), MimeTypesMap.GetMimeType(S3Path), fileName);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.