2012-12-01 35 views
1

我上傳圖片:爲什麼不找一個資源

[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我有錯誤:

The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

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

我究竟做錯了什麼?

+6

是在您的網址的根內容?您正在請求/內容中的圖片,但是當您上傳圖片時,您已將其上傳到〜/ content/...他們是否是同一位置? – Brettski

+0

爲什麼在這個問題上有兩個反對票? – Brettski

+0

我同意Brettski。這是一個完全有效的問題。從我+1。 –

回答

0

我鬆動。

圖像保存在ImageModel.ResizeAndSave並添加擴展名名爲.jpg

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

事實證明,該文件filename.jpg.jpeg

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時始終使用助手。

+0

這對我沒有幫助 – Mediator

+0

但是,您應該使用助手,如我的答案中所示,否則當您在IIS中部署時,代碼將會中斷。 –

+0

是的,我明白了。謝謝 – Mediator

相關問題