文件上传中的路径问题?

时间:2012-07-04 19:27:47

标签: c# asp.net-mvc file-upload

我正在尝试实现一个简单的文件上传,但遇到了一些麻烦。当我对路径进行硬编码时,它可以正常工作。但出于某种原因,当我尝试使用文件上传时,控制器名称将被附加到路径

硬编码路径(我想要得到的):

@"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>

可能导致此行为的原因是什么?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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, "#!#");
            }
        }
    }
}