asp.net-mvc – 以表格形式上传图片并在MVC 4上显示

存储用户上传的图像然后在我的网站上显示的最佳方式是什么?

>将其作为二进制文件存储在DB中.那怎么用`img`来展示呢?
我想我应该以某种方式将它写入目录,然后将其地址作为`img`的`src`属性传递.
>我可以将它存储在Web服务器的某个地方,将图像的地址存储在数据库中.那么我应该在`src`属性中简单地指定数据库中的地址.
>其他方式?!

在我看来,第二种方式更方便.
还有一个问题!
在这两种情况下如何以html格式上传此图像? @Html doesent有什么像@ Html.FileFor(…)那样我怎么能得到< input type ='file'/>的数据?在我的行动?
我感谢任何建议.

解决方法

in my opinion the second way is more convenient.

是的,在我看来也是如此.

In both case How Can I upload this images in html form?

满容易.与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中的文件上传工作.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....