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

You can save yourself the effort of the streams:

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, "#!#");
        }
    }
}

(bug) 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, "#!#");
        }
    }
}

编辑二

或复制到不同的路径:

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 回答