2016-10-24 14 views
0

私はasp.net mvcを使用して開発の初心者です。私は、ファイルダウンロードしようとしている(画像、PDFファイルを...)ここに私のコードですangularJSとasp.net mvcを使用してファイルをダウンロード

ASPコントローラで

[HttpPost] 
    public HttpResponseMessage Download(int id) 
    { 
     var db = new TutorialGEDEntities(); 

     Tutorial fileToDownload = db.Tutorials.Find(id); 
     string name = fileToDownload.filepath; 
     Debug.WriteLine("filepath " + name); 
     try 
     { 

      if (!string.IsNullOrEmpty(name)) 
      { 
       //var root = System.Web.HttpContext.Current.Server.MapPath(name); 
       var filePath = System.Web.HttpContext.Current.Server.MapPath(name); ; 
       char[] s = new char[name.Length - name.LastIndexOf("\\") - 1]; 
       name.CopyTo(name.LastIndexOf("\\")+1, s, 0, name.Length - name.LastIndexOf("\\")-1); 
       String fileName = new String(s); 
       using (MemoryStream ms = new MemoryStream()) 
       { 
        using (FileStream file = new FileStream(name, FileMode.Open, FileAccess.Read)) 
        { 
         Debug.WriteLine("file " + file.Length); 
         byte[] bytes = new byte[file.Length]; 
         file.Read(bytes, 0, (int)file.Length); 
         ms.Write(bytes, 0, (int)file.Length); 

         HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); 
         ByteArrayContent content = new ByteArrayContent(bytes.ToArray()); 
         httpResponseMessage.Content = content; 
         httpResponseMessage.Content.Headers.Add("x-filename", fileName); 
         httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); 
         httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
         httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName; 
         httpResponseMessage.StatusCode = HttpStatusCode.OK; 
         return httpResponseMessage; 
        } 
       } 
      } 
      return null; 
     } 
     catch (Exception ex) 
     { 
      Debug.WriteLine(ex.Data); 
      return null; 
     } 
    } 

と角コントローラで

   $http({ 
        method: 'POST', 
        url: 'Download', 
        data: { 'name': file.filepath }, 
        responseType: 'arraybuffer' 
       }).success(function (content, status, headers) { 
        headers = headers(); 
        console.log(content); 
        console.log(status) 
        var filename = headers['x-filename']; 
        var contentType = headers['content-type']; 

        var linkElement = document.createElement('a'); 
        try { 
         var blob = new Blob([content], { type: contentType }); 
         console.log(blob); 
         var url = URL.createObjectURL(blob); 
         console.log(url) 
         linkElement.setAttribute('href', url); 
         linkElement.setAttribute("download", filename); 

         var clickEvent = new MouseEvent("click", { 
          "view": window, 
          "bubbles": true, 
          "cancelable": false 
         }); 
         linkElement.dispatchEvent(clickEvent); 
        } catch (ex) { 
         console.log(ex); 
        } 
       }).error(function (data) { 
        console.log(data); 
       }); 
      }; 

を問題は私が手であります未定義のファイルと空のファイル私はそれがうまく動作するコードをデバッグ、aspコントローラからのデータは、よくHttpResponse int構造化されています。

私はそれを動作させるために何ができるのですか?ダウンロードを機能させるための他の提案は歓迎されます。

編集:

私はasp.netコントローラにダウンロード目的球を変えました。私はHttpResponseMessageクラスを使用しました。このソリューションでは、Responseクラスを使用しました。

ASPコントローラは以下のようになります。

[HttpPost] 
    public void Download(String name) 
    { 
     Debug.WriteLine("filepath " + name); 

      if (!string.IsNullOrEmpty(name)) 
      { 
       char[] s = new char[name.Length - name.LastIndexOf("\\") - 1]; 
       name.CopyTo(name.LastIndexOf("\\")+1, s, 0, name.Length - name.LastIndexOf("\\")-1); 
       String fileName = new String(s); 
       //var filePath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/") + fileName; 

       Response.ContentType = "application/octet-stream"; 

       Response.AppendHeader("Content-Disposition", fileName); 
       Response.AppendHeader("X-FileName", fileName); 
       Response.TransmitFile(name); 
       Response.End(); 

       } 

    } 
+0

私は「オブジェクトは、このVaRのclickEvent =新しいMouseEventの上でこのアクションsupporしません取得( "クリック"、{ "ビュー":ウィンドウを、 "泡":真、 "解約":偽 }); – Exzile

答えて

1
  $http({ 
       method: 'POST', 
       url: 'Download', 
       data: { 'name': file.filepath }, 
       responseType: 'arraybuffer', 
   transformRequest: angular.identity, 
  }). 

angular.identity(それをシリアル化するように)私たちのデータに何もする角度防ぎます。

+0

あなたの答えをありがとうが、これは私にこのエラーを与えた無効なJSONプリミティブ:オブジェクト。 –

+0

説明:現在のWeb要求の実行中に、未処理の例外が発生しました。エラーの詳細とコード内のどこで発生したのかについては、スタックトレースを参照してください。 –

関連する問題