我的用戶擁有需要經過身份驗證的用戶下載的私有文件。我的服務器首先使用它自己的S3 app_id/secret_token憑證從S3下載文件。然後構建下載的文件並使用Rails的send_data方法發送給客戶端。
紅寶石(on Rails的):
# documents_controller.rb
def download
some_file = SomeFile.find(params[:id])
# download file from AWS S3 to server
data = open(some_file.document.url)
# construct and send downloaded file to client
send_data data.read, filename: some_file.document_identifier, disposition: 'inline', stream: 'true'
end
本來我是想這樣做直接從HTML模板觸發下載。
HTML:
<!-- download-template.html -->
<a target="_self" ng-href="{{ document.download_url }}" download="{{document.file_name}}">Download</a>
看起來很簡單,但問題是,角的$ HTTP攔截不抓住這個類型的外部鏈接的點擊,因此相應的頭不追加用於服務器端認證。結果是401未授權錯誤。
相反,我需要使用ng-click觸發下載,然後從角度控制器執行$ http.get()請求。
HTML:
<!-- download-template.html -->
<div ng-controller="DocumentCtrl">
<a ng-click="download(document)">Download</a>
</div>
的Javascript:
// DocumentCtrl.js
module.controller("DocumentCtrl",
[ "$http", "$scope", "FileSaver", "Blob",
function($http, $scope, FileSaver, Blob) {
$scope.download = function(document) {
$http.get(document.download_url, {}, { responseType: "arraybuffer" })
.success(function(data) {
var blob = new Blob([data], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
FileSaver.saveAs(blob, document.file_name);
});
};
}]);
FileSaver是一個簡單的庫保存使用的斑點(在客戶端上,很明顯)文件。
這讓我通過我的身份驗證問題,但導致文件以不可讀/無法格式保存/下載到客戶端。
爲什麼文件以不可用格式下載?
在此先感謝。
您是否必須使用FileSaver?你嘗試過'window.navigator.msSaveOrOpenBlob'和'window.open(objectUrl)'嗎? – Kyle
我不需要使用FileSaver,但使用window.navigator.msSaveOrOpenBlob和window.open(objectUrl)都會導致相同的問題:不可讀的文件格式。它仍然是包裝/構造的文件被Blob重新包裝/構造的情況。 – mikeborgh