2017-06-23 9 views
1

ファイルの応答を送信してユーザーをリダイレクトすることはできますか?どのような手順が必要ですか?誰かがリソースや概要へのリンクを与えることができたらうれしいです。 私のシナリオでは、ユーザーである私は、次のようにしようとした後、アクションメソッドは、ユーザーASP.Net MVC5ダウンロードファイルとrediredt

をダウンロードして、リダイレクトするファイルを送信、ファイルのアクションメソッドをダウンロードするための要求を送信します。

[HttpGet] 
    [Authorize] 
    public ActionResult DownloadFile() 
      { 

       var currentUserId = User.Identity.GetUserId(); 
       var invoices = _context.Invoices 
.Where(x => x.OwnerId == currentUserId).ToList(); 

       var directory = HttpContext.Server.MapPath("~/Temp"); 
       var timeStamp = DateTime.Now.ToString("yyyy_MM_dd_HH_mm"); 

       var fileName = string.Concat("myfile", "_", timeStamp, ".xlsx"); 
       var filePath = Path.Combine(directory, fileName); 

       FileService fs = new FileService(); 
       var file = fs.GenerateExcelFile(filePath, invoices); 

        Response.ClearHeaders(); 
        Response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName); 
        var contentType ="application/excel"; 
        return File(filePath ,contentType); 

        // HOW do I send download file and return to view ?? 

      } 
+1

クライアントとサーバーのアーキテクチャでは、応答が完了すると完了です。私が理解する限り、ファイルに応答したり、別のページにリダイレクトすることはできません。 JavascriptとおそらくAjaxを使った回避策を考えてみましょう。 – derloopkat

+0

@derloopkat、ありがとう、私はjavascriptを使用していくつかの関連スレッドをスクラッチします。 – ryan

答えて

0

あなたのビューでは、このコードを追加します。 jQueryと、添付ファイルのヘッダーを含むファイルを返すWeb APIを使用します。タイムアウト機能は、ファイルがサーバーから要求されるまでに時間がかかります。

<a id="link" href="#">Click here to download</a> 
<script type="text/javascript"> 
    $('#link').click(function (e) { 
     e.preventDefault(); //prevent browser to follow link 
     setTimeout(function() { //Redirected to new page in 2 sec 
      window.location.href = 'http://localhost:2981/Home/NewPage' 
     }, 2000); 
     window.location.href = 'http://localhost:2981/api/files/get/'; 
    }); 
</script> 

私の場合のWeb APIは、ダミーメソッドです。重要な部分はヘッダーです。ファイルにリダイレクトされるのではなく、ファイルをダウンロードするようユーザーに指示する必要があります。したがって、添付ファイルヘッダーを追加する必要があります。

public class FilesController : ApiController 
{ 

    [HttpGet] 
    public HttpResponseMessage Get() 
    { 
     string result = "this is the file content"; 
     var response = new HttpResponseMessage(HttpStatusCode.OK); 
     response.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain"); 
     response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
     return response; 
    } 
} 
関連する問題