我有一个Controller.cs,它会返回如下文件:
return File(file, "application/xml");
最终将文件以以下形式返回给我的js:
.then(function (file) {
window.open(uri, '_blank');
downloadFile(file);
});
window.open在我的浏览器中显示xml文件,但我想下载它附带的文件。
我尝试了许多解决方案以使其工作,但似乎文件不是我期望的那样。
我尝试了这些:
1。
function objToString(obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
console.log(objToString(file));
//Output:
0::<
1::?
2::x
3::m
4::l
5::
6::v
7::e
8::r
9::s
10::i
11::o
etc..
2:
console.log(file.toJSON());
//output:
Object(13799) [ "<", "?", "x", "m", "l", " ", "v", "e", "r", "s", … ]
3。
console.log(file.toString());
//output:
[object Object]
4。
console.log(JSON.stringify(file));
//output:
{"0":"<","1":"?","2":"x","3":"m","4":"l","5":" ","6":"v","7":"e","8":"r","9":"s","10":"i","11":"o","12":"n","13":"=","14":"\"","15":"1","16":".","17":"0","18":"\"","19":" ","20":"e","21":"n","etc..
我想使用这种方法下载:
if (window.navigator && window.navigator.msSaveBlob) {
e.preventDefault();
navigator.msSaveBlob(new Blob([file], { type: 'application/xml' }), "file.xml")
}
else {
var link = document.createElement("a");
link.download = "file.xml";
link.href = "data:application/xml," + encodeURIComponent(file);
link.click();
}
我该怎么做才能使其正常工作?如何解析文件?
答案 0 :(得分:0)
有一个可行的解决方案:
function download(file) {
var blob = new Blob([new Uint8Array(file.data)], { type: 'application/xml' });
var name = 'Infopath.xml';
if (window.navigator.msSaveOrOpenBlob) { // for IE 11 en Edge
window.navigator.msSaveBlob(blob, name);
}
else //Other browsers
{
var URL = window.URL || window.MozURL || window.webkitURL || window.MSURL || window.OURL;
var anchor = document.createElement('a');
anchor.href = URL.createObjectURL(blob);
anchor.download = name;
document.body.appendChild(anchor);
anchor.target = '_blank';
anchor.click();
document.body.removeChild(anchor);
}
}