为什么不找资源

时间:2012-12-01 07:58:55

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

我正在上传图片:

[HttpPost]
public ActionResult Create(PlaceViewModel model)
{
    if (ModelState.IsValid)
    {
        string fileName = Guid.NewGuid().ToString() + ".jpg";
        string serverPath = Server.MapPath("~");
        string imagesPath = serverPath + "Content\\Uploads\\";
        string thumbPath = imagesPath + "Thumb\\";
        string fullPath = imagesPath + "Full\\";
        ImageModel.ResizeAndSave(thumbPath, fileName, model.ImageUploaded.InputStream, 100, true);
        ImageModel.ResizeAndSave(fullPath, fileName, model.ImageUploaded.InputStream, 600, true);

        model.Image = fileName;

        var place = new Place();
        model.ConvertToData(place);

        _placeRepository.Add(place);
        _placeRepository.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(model);
}

文件上传并在磁盘中存在物理

我正在用html调用图片:

<img height="100px" src="/Content/Uploads/Thumb/833c4384-884d-4250-982c-d5df0fa875ef.jpg" width="100px"/>

但我没有看到这张照片。

如果我致电localhost:23354/Content/Uploads/Thumb/833c4384-884d-4250-982c-d5df0fa875ef.jpg我有错误:

  

无法找到资源。描述:HTTP 404.资源   你正在寻找(或其中一个依赖)本来可以   删除,更改名称或暂时不可用。请   查看以下URL并确保拼写正确。

     

请求的网址:   /Content/Uploads/Thumb/833c4384-884d-4250-982c-d5df0fa875ef.jpg

我做错了什么?

2 个答案:

答案 0 :(得分:2)

如果您在虚拟目录中的IIS中运行,则应预先指定虚拟目录。您永远不应在视图中对网址进行硬编码。始终使用帮助者:

<img height="100px" src="@Url.Content("~/Content/Uploads/Thumb/833c4384-884d-4250-982c-d5df0fa875ef.jpg")" width="100px"/>

现在,当您在没有虚拟目录的情况下在本地运行时,帮助程序将生成:

/Content/Uploads/Thumb/833c4384-884d-4250-982c-d5df0fa875ef.jpg

当您在IIS中将应用程序上传到虚拟目录中时,帮助程序将再次生成正确的URL:

/AppName/Content/Uploads/Thumb/833c4384-884d-4250-982c-d5df0fa875ef.jpg

正如您所看到的,您永远不应该对网址进行硬编码。您的javascript文件中的网址相同。在ASP.NET MVC应用程序中处理URL时始终使用帮助程序。

答案 1 :(得分:0)

我放松了。

保存在ImageModel.ResizeAndSave中的图片,并附加名称扩展名“.jpg”

newImage.Save(savePath + fileName + ".jpg", ImageFormat.Jpeg);

事实证明该文件是filename.jpg.jpeg

相关问题