在我看来,第二种方式更方便。
是的,在我看来也是如此。
在这两种情况下,如何以 html 形式上传这些图像?
相当容易。与往常一样,在 ASP.NET MVC 应用程序中,您从设计视图模型开始:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
那么您可以拥有一个具有 2 个操作的控制器(一个呈现视图,另一个处理文件上传):
public class HomeController: Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// the user didn't upload any file =>
// render the same view again in order to display the error message
return View(model);
}
// at this stage the model is valid =>
// you could handle the file upload here
// let's generate a filename to store the file on the server
var fileName = Guid.NewGuid().ToString() + Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
// store the uploaded file on the file system
file.SaveAs(path);
// TODO: now you could store the path in your database
// and finally return some ActionResult
// to inform the user that the upload process was successful
return Content("Thanks for uploading. Your file has been successfully stored on our server");
}
}
最后,您将拥有一个相应的强类型视图,该视图将包含表单以上传文件:
@model MyViewModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
@Html.LabelFor(x => x.File)
@Html.TextBoxFor(x => x.File, new { type = "file" })
@Html.ValidationMessageFor(x => x.File)
</div>
<button type="sybmit">Upload</button>
}
另外,我建议您阅读Phil Haack's blog post
说明 ASP.NET MVC 中文件上传的工作原理。