1

簡単なファイルアップロードを実装しようとしていますが、問題があります。パスをハードコーディングすると、正常に機能します。しかし、何らかの理由で、ファイルアップロードを使用しようとすると、コントローラー名がパスに追加されます

ハードコードされたパス(私が取得しようとしているもの):

@"C:\Users\Scott\Documents\The Business\MasterSpinSite\MasterSpin\MasterSpin\LOADME.txt"

パス私は例外を取得しています(「appz」コントローラー名に注意してください):

C:\Users\Scott\Documents\The Business\MasterSpinSite\MasterSpin\MasterSpin\appz\LOADME.txt'

私のコントローラー

public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)
    {

        if (file.ContentLength > 0)
        {

            string filePath = Request.MapPath(file.FileName);

            string input = System.IO.File.ReadAllText(filePath);
            string[] lines = Regex.Split(input, "#!#");
           // ...... do stuff

        }

私の見解

<form action="" method="post" enctype="multipart/form-data">

  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />

<input type="submit" value="LOAD ME!">

 </form>

この動作の原因は何ですか?

4

2 に答える 2

1

ストリームの労力を節約できます。

string filename = Request.Files["file"].FileName;
string filePath = Path.Combine(Server.MapPath("~/YourUploadDirectory"), filename);

HttpPostedFileBase postedFile = Request.Files["file"] as HttpPostedFileBase;
postedFile.SaveAs(filePath);

string input = File.ReadAllText(filePath);
于 2012-07-04T20:50:47.923 に答える
0

これを試して:

public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)

    if (file.ContentLength > 0)
    {
        var filePath = System.IO.Path.GetFileName(file.FileName);
        using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
        {
            var input = sr.ReadToEnd();
            var lines = Regex.Split(input, "#!#");
        }
    }
}

(バグ) System.IO.Path.GetFileName(file.FileName)ファイル名を返す

編集

System.IO.Path.GetFileName(file.FileName)のための変更Server.MapPath(file.FileName)

public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)

    if (file.ContentLength > 0)
    {
        var filePath = Server.MapPath(file.FileName);
        using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
        {
            var input = sr.ReadToEnd();
            var lines = Regex.Split(input, "#!#");
        }
    }
}

編集II

または別のパスにコピーします。

public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)

    if (file.ContentLength > 0)
    {
        var fileName = System.IO.Path.GetFileName(file.FileName);
        var fileUpload = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        file.SaveAs(fileUpload);
        if (System.IO.File.Exists(fileUpload)) 
        {
            using (System.IO.StreamReader sr = new System.IO.StreamReader(fileUpload))
            {
                var input = sr.ReadToEnd();
                var lines = Regex.Split(input, "#!#");
            }
        }
    }
}
于 2012-07-04T20:03:54.330 に答える