I have created a blog with ASP.NET MVC 4.
The problem is when my url is not localhost I cannot see any pictures inside my Posts, because they get wrong url. The url of the post can be:
1.localhost/post/2015/4/name_of_post
or
2.localhost/archive/name_of_post
or
3.localhost/name_of_category/name_of_post
,
and inside the post is the picture.
The picture must have this
url:localhost/App_Files/Upload/name_of_image.jpg
but gets instead this
url:localhost/post/2015/4/App_Files/Upload/name_of_image.jpg
or
localhost/archive/name_of_post
or
localhost/name_of_category/App_Files/Upload/name_of_image.jpg
.
If you use the right url you will see the picture in browser. I use tinymce to add pictures inside the the post when i create it. The picture is saved as file in the App_Files/Upload folder. The post is inserted in a row as html in sql database. I use this routeConfig
routes.MapRoute(
"Post",
"Archive/{year}/{month}/{title}",
new { controller = "Blog", action = "Post" }
);
and the uploadController is this:
using HotNews.ViewModels;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace HotNews.Controllers
{
public class UploadController : Controller
{
//
// GET: /Upload/
public ActionResult Index(string id)
{
//var url = HttpRuntime.AppDomainAppVirtualPath;
var url = ConfigurationManager.AppSettings["BlogUrl"];
return View(new UploadViewModel
{
baseUrl = url,
track = id
});
}
[HttpPost]
public ActionResult UploadFile()
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Files/Upload"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
public ActionResult ListFiles()
{
var fileData = new List<ViewDataUploadFileResults>();
DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/App_Files/Upload"));
if (dir.Exists)
{
string[] extensions = MimeTypes.ImageMimeTypes.Keys.ToArray();
FileInfo[] files = dir.EnumerateFiles()
.Where(f => extensions.Contains(f.Extension.ToLower()))
.ToArray();
if (files.Length > 0)
{
foreach (FileInfo file in files)
{
// var baseurl = ConfigurationManager.AppSettings["BlogUrl"];
var relativePath = VirtualPathUtility.ToAbsolute("~/App_Files/Upload") + "/" + file.Name;
fileData.Add(new ViewDataUploadFileResults()
{
// url = baseurl+relativePath,
url = relativePath,
name = file.Name,
type = MimeTypes.ImageMimeTypes[file.Extension],
size = Convert.ToInt32(file.Length)
});
}
}
}
return Json(fileData, JsonRequestBehavior.AllowGet);
}
}
}
Must I create an image hanndler?? Must I create a new routeconfig?? And what kind??