问题
I have the following PHP code which outputs a document from a web service:
$db->where('documentReference', $post->documentID);
$results = $db->getOne('documents');
$filelocation = 'doc/';
$file = $results['filename'];
header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Length: ' . filesize($filelocation.$file));
header('Content-disposition: attachment; filename="'.$file.'"');
readfile($filelocation.$file);
And on the front end..
APIService.registerUser($scope.formData).then(function(data){
var blob = new Blob([data.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
var config = {
data: blob,
filename: 'test.docx'
};
FileSaver.saveAs(config);
});
}
When I inspect the data returned from the API the document get returned fine, but when being saved it's always empty?
回答1:
When calling the API endpoint you need to set the responseType to array buffer like so:
var promise = $http.post('http://someurl', formData, {responseType: 'arraybuffer'});
return promise;
The file then gets saved properly.
来源:https://stackoverflow.com/questions/33100281/angularjs-filesaver-producing-empty-file