0

我正在使用ASP .Net MVC 4.0、vs10

在我的一个按钮单击事件中,我得到了这样的公司名称:

if (Request.Form["NAMEbtnImport"].Length > 0)
            {
                if (Request.Form["NAMEbtnUpload"].Length > 0 && Request.Form["NAMEtxtCompany"].Length > 0 )
                {
                    Session["CompanyName"] = Request.Form["NAMEtxtCompany"].ToString();
                    var x = collection.GetValue("NAMEbtnUpload"); 
                    filePath = x.AttemptedValue.ToString();
                    filePath = Request.Form["NAMEbtnUpload"];
                    string fileName = Path.GetFileName(filePath);                                        //var path = Path.Combine(Server.MapPath("~/Uploads"), filePath);
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Copy(filePath, Server.MapPath("~/Uploads/" + fileName));
                    }
                    companyName = Request.Form["NAMEtxtCompany"].ToString();
                    newFilePath = "Uploads/" + fileName;
                    ViewBag.CompanyName = companyName;
                }

这是我的 html:[编辑]

<input type="file" value="Upload" id="IDbtnUpload" name="NAMEbtnUpload"/>

这在 IE 中运行良好。文件路径已满。但在 Firefox 中,只有文件名正在接收。collection 和 request.form 都输出相同的数据。

这里有什么问题?对不起我糟糕的英语。

4

2 回答 2

2

Internet Explorer 将完整的文件路径发送到服务器;火狐没有。

这是浏览器作者的安全决定;你无能为力。

此外,您似乎正在File.Copy尝试将源上传文件复制到服务器上的某个位置。这仅用于复制本地文件 - 如果浏览器未在服务器上运行,它将不起作用!

你需要使用类似的东西

<asp:FileUpload  runat="server" ID="fuSample" />

在您的aspx文件中和

if (fuSample.HasFile)
{
    fuSample.SaveAs(
        Server.MapPathMapPath("~/Uploads/" + fuSample.FileName));
}

在你的代码隐藏中。

编辑:如果你被香草卡住了<input type="file" id="someID" ... />,试试

var file = this.Context.Request.Files["someID"];
if (file != null)
    file.SaveAs(Server.MapPathMapPath("~/Uploads/" + file.FileName));
于 2013-01-28T16:03:33.347 回答
1

您是否希望访问客户端计算机上的完整文件路径?你不应该这样做,也不应该这样做。

允许这样做的浏览器会带来安全风险。

如果我误解了您要做什么,请提前道歉!

编辑:要在 MVC 中处理文件上传,您可以在操作中使用 HttpPostedFileBase。像这样的东西:

<input type="file" name="file">

//POST FORM

        public ActionResult form_Post(HttpPostedFileBase file)
        {

              if (file != null && file.ContentLength > 0)
                {
                  file.SaveAs(mySavePath);
                 }
         }

编辑:以及更多关于文件保存的代码以供您最新评论:

                var fileName = Path.GetFileName(file.FileName);

                var path = Path.Combine(Server.MapPath("/myupload/path/"), fileName);

                if (!System.IO.File.Exists(path))
                {
                    file.SaveAs(path);
                }
于 2013-01-28T15:58:38.317 回答