Я не уверен, работает ли это в VS2012, но вы можете попробовать этот подход, который я использую в своих проектах MVC:
public action UploadFile(HttpPostedFileBase file) //this is how you get the file that was submited from your form
{
//so now that I have the file, i need to save it somewhere
//let's see if we have a folder for that, if not let's create it
if(!Directory.Exists(Server.MapPath("~/The path from the root of the app to the uploaded files folder/")))
{
Directory.CreateDirectory(Server.MapPath("~/The path from the root of the app to the uploaded files folder/"));
} //the ~ symbol is part of the code, it returns the physical path to the root of the application
var storage = Server.MapPath("~/The path from the root of the app to the uploaded files folder/");
//now we need a name, we can generate one as a GUID for example, or we can get it's own.
var fileName = file.FileName.Substring(file.FileName.LastIndexOf("\"), file.Name.Length + 1);
//Now you might have to play a bit with the substring arguments, I'm not sure i wrote that right,
//it might not need the +1 part, or it might need it on the LastIndexOf as well,
//anyway, now we have the name and the folder where to save our file, let's do that:
path = String.Format("{0}\{1}", storage, filename);
try
{
file.SaveAs(path); //Now the file is on the server,
//just save this path and whatever else you need in the database so you can
//grab it later.
}
catch
{
//do your exception handling here
}
Saving to database here...
}
Чтобы получить его, вы просто получаете этот объект из базы данных, как и любые другие объекты, например:
Предположим, вы делаете все в своем контроллере, чего не должны делать.
public Action GetFile(int id)
{
using(context = new YourDbContext())
{
var file = context.Files.FirstOrDefault(p => p.Id == id);
}
return View(file);
}
И поместите его путь для src
в html, чтобы отобразить изображение следующим образом:
<img src="@Model.path" /> //Considering that in your controller you will `return View(file);`
//So your file object is the model.
Еще одна вещь, я не уверен, что в путях вам понадобятся \ или /, я всегда ошибаюсь в первый раз, поэтому отлаживайте его при первом запуске, и если ваш путь выглядит как Folder1Folder2Folder3File
, это означает, что вам нужно его изменить :) .
Надеюсь, это помогло, удачи.
P.S. Возможно, есть лучшие способы сделать это, но я делаю так, и мне кажется, что это работает нормально.
person
Spluf
schedule
23.04.2016