在ASP.NET MVC中上传图片 [英] Uploading image in ASP.NET MVC

查看:243
本文介绍了在ASP.NET MVC中上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个上传的形式,我想通过我的信息,如图片和其他一些领域,但我不知道我该怎么上传图片。

I have a Upload form and I want to pass my information such as an Image and some other field but I don't know how can I upload Image ..

这是我的控制器code:

this is my controller code :

[HttpPost]
        public ActionResult Create(tblPortfolio tblportfolio)
        {
            if (ModelState.IsValid)
            {
                db.tblPortfolios.AddObject(tblportfolio);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(tblportfolio);
        }

这是我的看法code:

And this is my view code :

@model MyApp.Models.tblPortfolio

<h2>Create</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>tblPortfolio</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ImageFile)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.ImageFile, new { type = "file" })
            @Html.ValidationMessageFor(model => model.ImageFile)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Link)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Link)
            @Html.ValidationMessageFor(model => model.Link)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

现在我不知道我该怎么上传图片,并将其保存在服务器上..我怎么可以设置为 Guid.NewGuid(图片名); ?或者,我怎么可以设置图片的路径?

Now I don't know how can I upload Image and save it on server .. how can I set Image name by Guid.NewGuid(); ? Or how can I set Image Path ?

推荐答案

首先,你需要改变你的看法,包括以下内容:

Firstly, you'll need to change your view to include the following:

<input type="file" name="file" />

然后,你需要改变你的文章 ActionMethod HttpPostedFileBase ,像这样:

[HttpPost]
public ActionResult Create(tblPortfolio tblportfolio, HttpPostedFileBase file)
{
    //you can put your existing save code here
    if (file != null && file.ContentLength > 0) 
    {
        //do whatever you want with the file
    }
}

这篇关于在ASP.NET MVC中上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆