So habe ich ein Problem, wenn ich versuchte, Datei von Server-Antwort zu speichern.Javascript speichern Datei von HTTP-Antwort (Web API HttpResponseMessage)
Wenn ich versuche, die Datei von URL in meinem Browser alle Arbeit herunterzuladen, aber wenn ich versuchte, Anfrage von der Clint Seite zu senden, wird die Datei gespeichert, aber in der Datei gibt es "[Object object]" und wenn es eine PDF ist Datei wird nicht geöffnet.
Die Anforderung muss einen zusätzlichen Header enthalten, der die Schlüssel-ID des Clients enthält.
Hier mein Server-Code:
[HttpGet, IsAllowed(4,PageAction.Download)]
public HttpResponseMessage Download(string id)
{
var path = HttpContext.Current.Server.MapPath("~") + string.Format(@"Files\{0}.doc",id);
var stream = new FileStream(path, FileMode.Open);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = string.Format("{0}.doc", id);
return result;
}
Und hier meine clint Code:
function get() {
var defer = $q.defer();
$http.post('http://localhost:4704/api/file/download/1', { responseType: 'arrayBuffer' }).then(
function (data, status, headers, config) {
var results = {
data: data,
headers: data.headers(),
status: data.status,
config: data.config
};
defer.resolve(results);
}, function (data, status, headers, config) {
defer.reject(data);
});
return defer.promise;
}
$scope.download = function() {
get().then(function (response) {
var octetStreamMime = 'application/octet-stream';
var fileName = "Test.doc";
var contentType = response.headers["content-type"] || octetStreamMime;
try {
var blob = new Blob([response.data], { type: contentType });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
} catch (exc) {
console.log("Save Blob method failed with the following exception.");
console.log(exc);
}
}, function (error) {
});
Darüber hinaus habe ich auch versucht, den folgenden Code:
$http.get("http://localhost:4704/api/file/download").then(function (res) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/doc;charset=utf-8,',
target: '_blank',
download: 'test.doc'
})[0].click();
})
wenn Sie versuchen, eine Datei herunterzuladen. Der Header muss ** content-type: multipart/form-data ** haben. Wenn Sie die PDF-Datei nicht richtig öffnen können, bedeutet dies, dass der Stream betroffen ist. also müssen Sie in den Konvertierungen herausfinden – Aravind