2016-04-09 11 views
0

フォームを使用して、ファイルとオプションフィールドをコントロールに投稿します。 HttpPostedFileBaseファイルを3つのメソッドに渡しています。それらのうちの2つでは、それはヌルではなく、最後のものである。私はそれをどこにでも置いてはいけません。 これは、コード...StreamReader is null

マイフォーム

<form onsubmit="return check();" action="" method="post" enctype="multipart/form-data" class="form-inline"> 
    <div class="form-group"> 
     <label for="languages">Choose the language combination for translating the E BOOK </label> 
     <select class=" input-large" name="languages" id="languages"> 

      <option value="en-fr">ENGLISH TO FRENCH</option> 
      <option value="en-de">ENGLISH TO GERMAN</option> 
      <option value="en-pt">ENGLISH TO PORTUGUESE</option> 
      <option value="en-ru">ENGLISH TO RUSSIAN</option> 
      <option value="en-sr">ENGLISH TO SERBIAN</option> 
      <option value="en-es">ENGLISH TO SPANISH</option> 
      <option value="fr-en">FRENCH TO ENGLISH</option> 
      <option value="de-en">GERMAN TO ENGLISH</option> 
      <option value="de-sr">GERMAN TO SERBIAN</option> 
      <option value="pt-en">PORTUGUESE TO ENGLISH</option> 
      <option value="ru-en">RUSSIAN TO ENGLISH</option> 
      <option value="es-en">SPANISH TO ENGLISH</option> 
     </select> 
    </div> 


    <div class="form-inline"> 
     <input type="file" class="btn btn-success" name="file" id="file" accept="text/plain, application/pdf"> 
     <input type="submit" class="btn btn-success" value="Upload PDF/TXT document" name="submit"> 
    </div> 
</form> 

これは、フォーム

を扱うのcontrolerの一部であり、これは私の全体のcontrolerクラスです

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Net.Mail; 
using System.Web; 
using System.Web.Mvc; 
using System.Data; 

namespace TranslationEmbedder.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      return View(); 
     } 

     [HttpPost] 
     public ActionResult Index(HttpPostedFileBase file, string languages) 
     { 

      if (file != null) 
      { 
       if (file.ContentLength > 0) 
       { 
        //var fileName = Path.GetFileName(file.FileName); 
        var fileNameNoExtension = Path.GetFileNameWithoutExtension(file.FileName); 
        //var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
        //file.SaveAs(path); 
        HashSet<string> set=null; 
        var fileExtension = Path.GetExtension(file.FileName); 

        if (fileExtension.ToLower().Equals(".txt")) 
        { 
         set = HomeController.geUniqueWordsInEbook(file); 
        } 

        if (fileExtension.ToLower().Equals(".pdf")) 
        { 
         set = HomeController.geUniqueWordsInEbookPdf(file); 
        } 

        if (set == null) 
        { 
         return RedirectToAction("Index"); 
        } 

        Dictionary<string, string> dic = HomeController.LoadCsvDictionary(set, languages); 

        if (fileExtension.ToLower().Equals(".txt")) 
        { 
         Response.Clear(); 
         Response.AddHeader("Content-Disposition", "attachment; filename=" + fileNameNoExtension + ".html"); 
         Response.ContentType = "text/html"; 
         HomeController.writeHtmlEbookFromTxt(file, dic, languages); 
         Response.End(); 
        } 

        if (fileExtension.ToLower().Equals(".pdf")) 
        { 
         Response.Clear(); 
         Response.AddHeader("Content-Disposition", "attachment; filename=" + fileNameNoExtension + ".html"); 
         Response.ContentType = "text/html"; 
         writeHtmlEbookFromPdf(file, dic, languages); 
         Response.End(); 
        } 


        // Not sure what else to do here 
        return Content(String.Empty); 



       } 
      } 

      return RedirectToAction("Index"); 
     } 

     private void writeHtmlEbookFromPdf(HttpPostedFileBase file, Dictionary<string, string> dic,string languageCode) 
     { 


     } 

     private static void writeHtmlEbookFromTxt(HttpPostedFileBase file, Dictionary<string, string> dic, string languageCode) 
     { 


       var fileNameNoExtension = Path.GetFileNameWithoutExtension(file.FileName); 

        System.Web.HttpContext.Current.Response.Write(""); 
        System.Web.HttpContext.Current.Response.Write("<!DOCTYPE html><html>"); 
        System.Web.HttpContext.Current.Response.Write("<head><META HTTP-EQUIV='content-type' CONTENT='text/html; charset=utf-8'><title>" + fileNameNoExtension + "</title>"); 
        System.Web.HttpContext.Current.Response.Write("<script>"); 
        System.Web.HttpContext.Current.Response.Write("function speakIt(b)"); 
        System.Web.HttpContext.Current.Response.Write("{"); 
        System.Web.HttpContext.Current.Response.Write("if (document.getElementById(\"myCheck\").checked) {"); 
        System.Web.HttpContext.Current.Response.Write("if ('speechSynthesis' in window) {"); 
        System.Web.HttpContext.Current.Response.Write("var sometext=b;"); 
        System.Web.HttpContext.Current.Response.Write("var msg = new SpeechSynthesisUtterance();"); 
        System.Web.HttpContext.Current.Response.Write("var voices = window.speechSynthesis.getVoices();"); 
        System.Web.HttpContext.Current.Response.Write("msg.text = sometext;"); 


        string[] toSpeak = languageCode.Split('-'); 

        switch (toSpeak[0]) 
        { 
         case "de"://German 
          languageCode = "de-DE"; 
          break; 
         case "en"://English 
          languageCode = "en-GB"; 
          break; 
         case "es"://Spanish 
          languageCode = "es-ES"; 
          break; 
         case "fr"://French 
          languageCode = "fr-FR"; 
          break; 
         case "ru"://Russian 
          languageCode = "ru"; 
          break; 
         case "pt"://Portuguese - Portugal 
          languageCode = "pt-PT"; 
          break; 
         case "sr"://Serbian 
          languageCode = "sr-SP"; 
          break; 
         case "ja"://Japanese 
          languageCode = "ja"; 
          break; 
         case "he"://Hebrew 
          languageCode = "he"; 
          break; 
         case "it"://Italian - Italy 
          languageCode = "it-IT"; 
          break; 
         case "el"://Greek 
          languageCode = "el"; 
          break; 
         case "zh"://Chinese - China 
          languageCode = "zh-CN"; 
          break; 
         case "ar"://Arabic - Egypt 
          languageCode = "ar-EG"; 
          break; 
         case "hy"://Armenian 
          languageCode = "hy"; 
          break; 
         case "eu"://Basque 
          languageCode = "eu"; 
          break; 
         case "be"://Belarusian 
          languageCode = "be"; 
          break; 
         case "cs"://Czech 
          languageCode = "cs"; 
          break; 
         case "da"://Danish 
          languageCode = "da"; 
          break; 
         case "et"://Estonian 
          languageCode = "et"; 
          break; 
         case "mk"://FYRO Macedonia 
          languageCode = "mk"; 
          break; 
         case "hu"://Hungarian 
          languageCode = "hu"; 
          break; 
         case "is"://Icelandic 
          languageCode = "is"; 
          break; 
         case "hi"://Hindi 
          languageCode = "hi"; 
          break; 
         case "id"://Indonesian 
          languageCode = "id"; 
          break; 
         case "kk"://Kazakh 
          languageCode = "kk"; 
          break; 
         case "ko"://Korean 
          languageCode = "ko"; 
          break; 
         case "lv"://Latvian 
          languageCode = "lv"; 
          break; 
         case "lt"://Lithuanian 
          languageCode = "lt"; 
          break; 
         case "pl"://Polish 
          languageCode = "pl"; 
          break; 
         case "sk"://Slovak 
          languageCode = "sk"; 
          break; 
         case "sl"://Slovenian 
          languageCode = "sl"; 
          break; 
         case "sv"://Swedish - Sweden 
          languageCode = "sv-SE"; 
          break; 
         case "tr"://Turkish 
          languageCode = "tr"; 
          break; 
         case "uk"://Ukrainian 
          languageCode = "uk"; 
          break; 
         case "vi"://Vietnamese 
          languageCode = "vi"; 
          break; 
         //...add more language support 
         default: 
          languageCode = "de-DE"; 
          break; 
        } 

        System.Web.HttpContext.Current.Response.Write("msg.lang = '" + languageCode + "';"); 
        System.Web.HttpContext.Current.Response.Write("speechSynthesis.speak(msg);"); 
        System.Web.HttpContext.Current.Response.Write("}"); 
        System.Web.HttpContext.Current.Response.Write("}"); 
        System.Web.HttpContext.Current.Response.Write("}"); 

        System.Web.HttpContext.Current.Response.Write("</script>"); 

        System.Web.HttpContext.Current.Response.Write("<style>"); 

        System.Web.HttpContext.Current.Response.Write("#ebook {"); 
        System.Web.HttpContext.Current.Response.Write(" margin: auto;"); 
        System.Web.HttpContext.Current.Response.Write("width: 90%;font-size: 200%;@page {counter-increment: page;counter-reset: page 1;@top-right {content: \"Page \" counter(page) \" of \" counter(pages);}}"); 
        System.Web.HttpContext.Current.Response.Write("text-align: left;line-height:1.5;font-family: 'Merriweather', Georgia, 'Times New Roman', Times, serif;"); 
        System.Web.HttpContext.Current.Response.Write("vertical-align: middle;"); 
        System.Web.HttpContext.Current.Response.Write("word-wrap: break-word;"); 
        System.Web.HttpContext.Current.Response.Write("border:3px solid #8AC007;"); 
        System.Web.HttpContext.Current.Response.Write("padding: 10px;"); 
        System.Web.HttpContext.Current.Response.Write("}"); 

        System.Web.HttpContext.Current.Response.Write("#header-wrap {"); 
        System.Web.HttpContext.Current.Response.Write("position: fixed;"); 
        System.Web.HttpContext.Current.Response.Write("text-align: center;"); 
        System.Web.HttpContext.Current.Response.Write("background-color: #8AC007;"); 
        System.Web.HttpContext.Current.Response.Write("color: white;"); 
        System.Web.HttpContext.Current.Response.Write("height: 25px;"); 
        System.Web.HttpContext.Current.Response.Write("top: 0;"); 
        System.Web.HttpContext.Current.Response.Write("width: 100%;"); 
        System.Web.HttpContext.Current.Response.Write("z-index: 100;"); 
        System.Web.HttpContext.Current.Response.Write("}"); 

        System.Web.HttpContext.Current.Response.Write("</style>"); 
        System.Web.HttpContext.Current.Response.Write("</head><body></br>"); 

        System.Web.HttpContext.Current.Response.Write("<div id='header-wrap'></br>"); 
        System.Web.HttpContext.Current.Response.Write("<span>ENABLE/DISABLE TEXT TO SPEECH : <input type=\"checkbox\" name=\"myCheck\" id=\"myCheck\" checked=\"checked\"></span></br></br>"); 
        System.Web.HttpContext.Current.Response.Write("</div>"); 

        System.Web.HttpContext.Current.Response.Write("<div id='ebook'>"); 




      System.IO.StreamReader reader = new System.IO.StreamReader(file.InputStream); 
      string line=""; 
      while ((line = reader.ReadLine()) != null) 
       { 


         string[] words = line.Split(' '); 

         foreach (string word in words) 
         { 
          string cleanWord = word.Replace(".", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("ß", "ss").Replace("?", "").Replace("!", "").Replace("«", "").Replace("»", "").Replace("[", " ").Replace("]", " ").Replace("(", " ").Replace(")", " ").Replace(",,", " ").Replace("\"", " ").Replace("-", " ").ToLower(); 
          string value = ""; 
          if (dic.ContainsKey(cleanWord)) 
           value = dic[cleanWord]; 

          System.Web.HttpContext.Current.Response.Write("<span onclick =\"alert('" + value + "');speakIt('" + cleanWord + "'); \" >" + " " + word + " " + "</span>"); 
         } 

         System.Web.HttpContext.Current.Response.Write("</br>"); 


        } 
        System.Web.HttpContext.Current.Response.Write("</div></body></html>"); 


       reader.Close(); 




     } 
     private static Dictionary<string, string> LoadCsvDictionary(HashSet<string> uniqueEbookWords,string language) 
     { 

      string languageFile = AppDomain.CurrentDomain.GetData("DataDirectory")+ "\\languages\\"+ language + ".csv"; 
      Dictionary<string, string> d = new Dictionary<string, string>(); 



      using (var reader = new StreamReader(System.IO.File.OpenRead(@languageFile))) 
      { 

       while (!reader.EndOfStream) 
       { 
        var line = reader.ReadLine(); 
        var values = line.Split(','); 

        if (uniqueEbookWords.Contains(values[0].ToLower())) 
        { 
         if (!d.ContainsKey(values[0].ToLower())) 
          d.Add(values[0].ToLower(), values[1].ToLower()); 
        } 

       } 


      } 


      return d; 
     } 

     private static HashSet<string> geUniqueWordsInEbook(HttpPostedFileBase file) 
     { 
      //make two options one for PDF and one for TXT uploaded ebook... 
      int counter = 0; 
      string line; 

      HashSet<string> uniqueWords = new HashSet<string>(); 

      System.IO.StreamReader file1 =new System.IO.StreamReader(file.InputStream); 


      while ((line = file1.ReadLine()) != null) 
      { 
       string[] words = line.Split(' '); 
       foreach (string word in words) 
       { 
        string cleanWord = word.Replace(".", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("ß", "ss").Replace("?", "").Replace("!", "").Replace("«", "").Replace("»", "").Replace("[", " ").Replace("]", " ").Replace("(", " ").Replace(")", " ").Replace(",,", " ").Replace("\"", " ").Replace("-", " ").ToLower(); 
        uniqueWords.Add(cleanWord); 

       } 

       counter++; 
      } 

      file1.Close(); 


      return uniqueWords; 
     } 

     private static HashSet<string> geUniqueWordsInEbookPdf(HttpPostedFileBase file) 
     { 
      //make two options one for PDF and one for TXT uploaded ebook... 
      int counter = 0; 
      string line; 

      HashSet<string> uniqueWords = new HashSet<string>(); 

      System.IO.StreamReader file1 = new System.IO.StreamReader(file.InputStream); 


      while ((line = file1.ReadLine()) != null) 
      { 
       string[] words = line.Split(' '); 
       foreach (string word in words) 
       { 
        string cleanWord = word.Replace(".", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("ß", "ss").Replace("?", "").Replace("!", "").Replace("«", "").Replace("»", "").Replace("[", " ").Replace("]", " ").Replace("(", " ").Replace(")", " ").Replace(",,", " ").Replace("\"", " ").Replace("-", " ").ToLower(); 
        uniqueWords.Add(cleanWord); 

       } 

       counter++; 
      } 

      file1.Close(); 


      return uniqueWords; 
     } 



     public ActionResult About() 
     { 
      ViewBag.Message = "Watch a video that will you more about www.TRANSLATION-EMBEDDER.com project."; 

      return View(); 
     } 

     public ActionResult Contact() 
     { 
      ViewBag.Message = "Feel free to contact us"; 

      return View(); 
     } 

     [HttpPost] 
     public ActionResult Contact(string email,string message) 
     { 

      if (email.Equals("")) 
      { 
       ViewBag.Message = "You must provide an email"; 
       return View(); 
      } 

      if (message.Equals("")) 
      { 
       ViewBag.Message = "You must provide the message"; 
       return View(); 
      } 

      ViewBag.Message = "The message is sent to us from the user with email: "+ email + ".We will responde as soon as possible. Have a nice day. "; 
      sendEmail(email, message); 
      return View(); 
     } 

     private void sendEmail(string email, string message) 
     { 
      //http://stackoverflow.com/questions/18326738/how-to-send-email-in-asp-net-c-sharp 

      /* 
      SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 25); 

      smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "tijanica"); 
      smtpClient.UseDefaultCredentials = true; 
      smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; 
      smtpClient.EnableSsl = true; 
      MailMessage mail = new MailMessage(); 

      //Setting From , To and CC 
      mail.From = new MailAddress(email, "Translation-Embedder.com"); 
      mail.To.Add(new MailAddress("[email protected]")); 
      mail.Body = message; 

      smtpClient.Send(mail); 
      */ 
     } 





    } 
} 

されており、方法でのみ

private static void writeHtmlEbookFromTxt(HttpPostedFileBase file, Dictionary<string, string> dic, string languageCode) 

私は読者のためにnullを取得し、ファイルをループするための私のループは この部分を実行したことがないん

System.IO.StreamReader reader = new System.IO.StreamReader(file.InputStream); 
      string line=""; 
      while ((line = reader.ReadLine()) != null) 
       { 


         string[] words = line.Split(' '); 

         foreach (string word in words) 
         { 
          string cleanWord = word.Replace(".", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("ß", "ss").Replace("?", "").Replace("!", "").Replace("«", "").Replace("»", "").Replace("[", " ").Replace("]", " ").Replace("(", " ").Replace(")", " ").Replace(",,", " ").Replace("\"", " ").Replace("-", " ").ToLower(); 
          string value = ""; 
          if (dic.ContainsKey(cleanWord)) 
           value = dic[cleanWord]; 

          System.Web.HttpContext.Current.Response.Write("<span onclick =\"alert('" + value + "');speakIt('" + cleanWord + "'); \" >" + " " + word + " " + "</span>"); 
         } 

         System.Web.HttpContext.Current.Response.Write("</br>"); 


        } 
        System.Web.HttpContext.Current.Response.Write("</div></body></html>"); 


       reader.Close(); 

私はすべてのものを試してみましたが、私は唯一の多くの方法で使用する理由同じコードを見ることができませんでしたこの場合、リーダーOBJECTにはnullが返されます。

+0

gitのハブリポジトリからソースコードをダウンロードすることができます。 'reader'変数は、ここに値を代入しているのでnullにすることはできません:' new StreamReader(file.InputStream) '。 –

+0

これは電子ブックの解析に使用されます。最初に私はすべてのユニークな単語を見つけます - これはHashSetコレクションに入れられ、HashSetは塗りつぶされています(チェックされています)...これらのユニークな単語のために私は翻訳がある辞書を取得します。そして最後に新しい本を書く時、私は電子本からユニークな言葉を得ていたときに私がすでに解析した同じ本を解析できません。 –

答えて

2

ファイルストリームを2回読み取ることはできません。あなたのgeUniqueWordsInEbookメソッドの中ではすでにfile.InputStreamを読んでいて、最後にそれを閉じてしまっています。これは、writeHtmlEbookFromTxtメソッドで2度目に読むことができない理由です。ファイルの内容を読みながら、1回の操作で2つの操作を行う必要があります。したがって、基本的にコードを再編成して、2つの操作がファイルストリームを読みながら1か所で行われるようにする必要があります。

アップロードされたファイルが非常に大きいと思わない場合は、その内容をメモリに(byte[])ロードすることができます。しかし、これは大容量のファイルに対する過度の攻撃となるでしょう。

アップロードしたファイルをウェブサーバーのディスクに保存し、このアップロードしたファイルから複数回読み取ることもできます。

+0

これを回避する方法はありますか?大きな方法を避けるためだけです –

+0

いいえ、方法はありません。アップロードされたファイルストリームは、読み取り専用です。一度読んだら、もう何もできません。それを逆にして再度読むことはできません。別の方法として、アップロードしたファイルをWebサーバーのディスクに保存し、それを何度も読むことができます。 –

+0

迅速な対応をありがとう! –

0

私はそれがあなたに役立つことを願っています。

のcontroler:

[HttpPost] 
    public ActionResult Create(HttpPostedFileBase FileData) 
    { 
     string fpath = ""; 
     try 
     { 
      if (Request.Files.Count > 0) 
      { 
       try 
       { 

        HttpPostedFileBase file = FileData; 
        string fname; 
        // want to check extension then use this method 
        //if (CheckExtension(file.ContentType.ToLower())) 
        //{ 
         // Checking for Internet Explorer 
         string extension = System.IO.Path.GetExtension(file.FileName); 

         if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") 
         { 
          string[] testfiles = file.FileName.Split(new char[] { '\\' }); 
          fname = Guid.NewGuid() + extension; //+ testfiles[testfiles.Length - 1]; 
         } 
         else 
         { 
          fname = Guid.NewGuid() + extension; //+ file.FileName; 
         } 

         // Get the complete folder path and store the file inside it. 
         fname = System.IO.Path.Combine(Server.MapPath("~/Content/"), fname); 
         file.SaveAs(fname); 

         return Content("Successfully Uploaded"); 
        //} 

       } 
       catch (Exception ex) 
       { 
        return Content("Error occurred. Error details: " + ex.Message); 
       } 
      } 

     } 
     catch (Exception) 
     { 
      return Content(Response.StatusCode.ToString() + " Bad Requrest error." + fpath); 
     } 
     return Content("No files selected."); 
    } 

    public bool CheckExtension(string Ext) 
    { 
     if (Ext == "application/pdf") 
     { 
      return true; 
     } 
     else if (Ext == "text/plain") 
     { 
      return true; 
     } 
     else if (Ext == "application/msword") 
     { 
      return true; 
     } 
     else if (Ext == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

ビュー:

@using (Html.BeginForm("Create", "Home", null, FormMethod.Post, new { id = "formU", enctype = "multipart/form-data" })){ 

<div class="modal-body"> 
    <div class="form-horizontal"> 
     @Html.ValidationSummary(true) 

     <label for="file">Filename:</label> 
     <input type="file" name="File" id="File" style="width:240px" /> 

     <div class="form-group"> 
      <input id="submit" type="submit" value="Submit" class="btn btn-success" /> 
     </div> 
    </div> 
</div>} 

あなたはまた、私は何か他のものがここにnullであることを疑うclick here

+1

ありがとう私は見てみましょう! –