在Firefox中获取完整的文件路径

时间:2013-01-28 15:51:03

标签: c# filepath

我正在使用 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中运行良好。 filepath已满。但在Firefox中,只接收文件名。 collection和request.form都输出相同的数据。

这里有什么问题?抱歉我的英语很差。

2 个答案:

答案 0 :(得分:2)

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

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

此外,您似乎正在使用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));

答案 1 :(得分: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);
                }
相关问题