2015-07-13 18 views
6

Tôi có tệp được lưu trữ trên bộ nhớ Azure mà tôi cần tải xuống từ bộ điều khiển ASP.NET MVC. Mã bên dưới thực sự hoạt động tốt.Cách tải xuống tệp PDF từ Azure trong ASP.NET MVC qua Hộp thoại Lưu

string fullPath = ConfigurationManager.AppSettings["pdfStorage"].ToString() + fileName ; 
Response.Redirect(fullPath); 

Tuy nhiên, PDF sẽ mở trong cùng một trang. Tôi muốn tập tin được tải xuống thông qua hộp thoại Lưu, vì vậy người dùng vẫn ở trên cùng một trang. Trước khi chuyển sang Azure, tôi có thể viết

return File(fullPath, "application/pdf", file); 

Nhưng với Azure không hoạt động.

Trả lời

1

Bạn có thể tải tệp xuống và sau đó nhấn vào trình duyệt web để người dùng có thể lưu.

var fileContent = new System.Net.WebClient().DownloadData(fullPath); //byte[] 

return File(fileContent, "application/pdf", "my_file.pdf"); 

đặc biệt overload này có một mảng byte, một loại nội dung và một tên tập tin đích.

5

Giả sử bạn có nghĩa là Azure Blob Storage khi bạn nói Azure Storage, có hai cách khác mà không thực sự tải xuống tệp từ bộ nhớ đến máy chủ web của bạn và cả hai đều liên quan đến thiết lập thuộc tính của bạn trên blob.

  1. Nếu bạn muốn tập tin luôn tải khi truy cập thông qua một địa chỉ URL, bạn có thể thiết lập thuộc tính Content-Disposition blob của.

    var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true); 
    var blobClient = account.CreateCloudBlobClient(); 
    var container = blobClient.GetContainerReference("container-name"); 
    var blob = container.GetBlockBlobReference("somefile.pdf"); 
    blob.FetchAttributes(); 
    blob.Properties.ContentDisposition = "attachment; filename=\"somefile.pdf\""; 
    blob.SetProperties(); 
    
  2. Tuy nhiên nếu bạn muốn file được tải về và đôi khi hiển thị trong trình duyệt thời điểm khác, bạn có thể tạo ra một chữ ký truy cập chia sẻ và ghi đè thuộc tính nội dung bố trí trong SAS và sử dụng URL SAS để tải xuống.

    var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true); 
        var blobClient = account.CreateCloudBlobClient(); 
        var container = blobClient.GetContainerReference("container-name"); 
        var blob = container.GetBlockBlobReference("somefile.pdf"); 
        var sasToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy() 
        { 
         Permissions = SharedAccessBlobPermissions.Read, 
         SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(15), 
        }, new SharedAccessBlobHeaders() 
        { 
         ContentDisposition = "attachment; filename=\"somefile.pdf\"", 
        }); 
        var downloadUrl = string.Format("{0}{1}", blob.Uri.AbsoluteUri, sasToken);//This URL will always do force download. 
    
Các vấn đề liên quan