Pleasssse幫我... 我有一個xlsm文件(excel與宏)在服務器端(c#),並希望下載它在客戶端(javascript,angularjs )。 所以..在服務器端控制器中,我返回一個HttpResponseMessage並在客戶端 - 下載它。在客戶端dowclock時xlsm文件被破壞
的問題是,打開已下載該文件時,它已損壞...
我做了一個簡短的測試案例來說明問題。
服務器端(C#ApiController):
[HttpGet]
public HttpResponseMessage exportDPs()
{
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
var stream = new FileStream(@"D:\excel\data.xlsm", FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "DPs.xlsm";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = stream.Length;
response.StatusCode = System.Net.HttpStatusCode.OK;
return response;
}
客戶端(JavaScript,angularjs):
$scope.exportDPs = function() {
$http({
method: GET,
url: '../Api/DPs/exportDPs',
}).success(function (data) {
var file = data;
var encodedUri = encodeURI(file);
var link = document.createElement("a");
link.setAttribute("href", "data:application/vnd.ms-excel.sheet.macroEnabled.12;charset=utf-8,\uFEFF" + encodedUri);
link.setAttribute("download", "DPs");
link.click();
})
}
檢查字節數,使字節的數量肯定沒有改變。您的流可能使用了破壞文件的默認ASCII編碼。您需要使用不會更改文件的UTF8編碼。我會使用以下內容:StreamReader stream = new StreamReader(@「D:\ excel \ data.xlsm」,Encoding.UTF8); – jdweng
爲什麼在文件內容前加上BOM('\ uFEFF')?這可能是導致你的問題。 –
此外,爲什麼不把代碼放到'href'屬性中,然後調用'.click()'。嘗試下載文件,然後將其作爲數據URI從鏈接提供,這無疑會使問題複雜化。 –