将文件上传到服务器

时间:2014-09-30 01:21:49

标签: c# asp.net-mvc-4

我正在为学校制作我的第一个MVC项目并遇到了这个问题:

我正在建立一个分类广告网页,用户可以上传他们想要销售的图片, 据我所知,最好的做法是将Image路径存储到Db表中,文件进入服务器中的文件。因此,通过该路径,我可以在网页中检索该特定图像。

问题是我只能将图像存储在本地计算机中,而不是存储在我发布项目的服务器中。

如何将此文件上传到服务器而不是本地计算机?

这是我的控制者:

public ActionResult CreateAnuncio( HttpPostedFileBase thePic)
{
    if (thePic != null && thePic.ContentLength > 0)
    {
        // string filePath = Path.Combine(Server.MapPath("http://example.com/Sites/mvc/classifieds/Images/slider"), Path.GetFileName(Nuevo.id + thePic.FileName)); // Does not Work

        string filePath = Path.Combine(Server.MapPath("~/Images/slider/"), Path.GetFileName(thePic.FileName)); //Works only for local saving

        thePic.SaveAs(filePath);
    }
    return RedirectToAction("Index");
}

基本上我得到的错误是:

  

http://example.com/Sites/mvc/classifieds/Images/slider'不是有效的虚拟路径。

以下是视图:

<form id="contact_form" method="post" action="/classifieds/CreateAnuncio" enctype="multipart/form-data">
    <input type="file" name="thePic"/>
    <input type="submit" value="Send">
 </form>

1 个答案:

答案 0 :(得分:2)

如果您在同一服务器上运行代码,则可以使用该文件夹的相对路径。

 var filePath = Path.Combine(Server.MapPath("~/classifieds/Images/slider"),
                                      Path.GetFileName(Nuevo.id + thePic.FileName)); 

如果它是网络中的共享位置,但可以从部署代码的服务器访问,那么它也应该可以正常工作

var filePath = Path.Combine(\\myFileServerName\files\",
                                        Path.GetFileName(Nuevo.id + thePic.FileName));

在这两种情况下,请确保更新目录的权限,以便ASP.NET可以写入该权限。

右键单击该文件夹,然后转到 properties-&gt; Security 并更新权限。

相关问题