ASP.Net MVC 5 图片上传到文件夹 [英] ASP.Net MVC 5 image upload to folder

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

问题描述

我有一个非常简单的 MVC5 应用程序,它有一个面向客户端的产品页面,我也使用了在 MVC 5 中构建的基本 CRUD 操作.

我有一个名为 Cakes.cs 的模型,因为客户销售蛋糕.很简单.这是该模型的代码:

 使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Web;命名空间 TastyCakes.Models{公开课蛋糕{公共 int CakesID { 获取;放;}公共字符串名称 { 获取;放;}公共字符串 描述 { 获取;放;}公共十进制价格{得到;放;}公共字符串 CakeImage{get { return Name.Replace(" ", string.Empty) + ".jpg";}}}}

如您所见,我正在使用计算属性为每个蛋糕创建一个图像名称.每个蛋糕我只需要一张图片.现在,当我在 CRUD 页面上编辑蛋糕时.我想添加一个简单的图像上传来上传图像(不需要调整大小或缩略图)但我想强加计算的属性名称.换句话说:无论用户给他们的照片起什么名字,我的上传代码都会将它重命名为 Cakes.Name 的任何名称(减去任何空格)+".jpg" 并将其保存到 "~Images/Cakes".

我只需要在实际的编辑页面上上传,所以此时蛋糕已经创建好了.重命名文件所需的所有信息都应该可以从编辑"页面获得并易于使用.以下是我的编辑页面代码:

编辑页面:

@model TastyCakes.Models.Cakes<div class="row"><div class="large-12 列"><hgroup class="title"><h1>编辑蛋糕</h1>@using (Html.BeginForm()){@Html.AntiForgeryToken()<div class="form-horizo​​ntal"><小时/>@Html.ValidationSummary(true)@Html.HiddenFor(model => model.CakesID)<div class="medium-12 column">@Html.LabelFor(model => model.Name)@Html.EditorFor(model => model.Name)@Html.ValidationMessageFor(model =>model.Name)

<div class="medium-12 column">@Html.LabelFor(model => model.Description)@Html.EditorFor(model => model.Description)@Html.ValidationMessageFor(model => model.Description)

<div class="medium-12 column">@Html.LabelFor(model =>model.Price)@Html.EditorFor(model => model.Price)@Html.ValidationMessageFor(model =>model.Price)

<div class="medium-12 column"><input type="submit" value="Save" class="tiny button"/>@Html.ActionLink("返回列表", "索引", null, new { @class = "tiny button" })

}@section 脚本 {@Scripts.Render("~/bundles/jqueryval")}

我已经审查了一些 html5 &ASP.Net 4 解决方案,但这太多了.我想要的很简单.任何想法或朝着正确方向的一脚将不胜感激.我不仅将这段代码用于客户网站,而且还包括在用于教授非常基本的 MVC 概念的虚构网站中.

解决方案

您需要:

然后将 HttpPostedFileBase 添加到您的模型中,其名称与 input 的名称相同.然后 HttpPostedFileModelBinder 将在调用操作之前从上传的文件中填充模型属性.请注意,我认为您可能应该在某处添加模型 ID,例如作为路径元素,以保证图像路径的唯一性,以免图像被意外覆盖.

http://www.prideparrot 上对此进行了相当完整的讨论.com/blog/archive/2012/8/uploading_and_returning_files

公共类蛋糕{...公共 HttpPostedFileBase 上传文件 { 获取;放;}}[HttpPost]public ActionResult Edit(Cakes cake)//我可能会在这里使用视图模型,而不是域模型{如果(模型状态.IsValid){如果 (cakes.UploadedFile != null){cakes.UploadedFile.SaveAs(Path.Combine("path-to-images-for-this-cake", cakes.CakeImage));}....}}

I have a very simple MVC5 application that has a product page for the client that I also am utilizing the basic CRUD operations that have been scaffolded out in MVC 5.

I have a Model called Cakes.cs because the client sells cakes. Pretty simple. Here is the code for that model:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace TastyCakes.Models
    {
        public class Cakes
        {
            public int CakesID { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public decimal Price { get; set; }

            public string CakeImage
            {
                get { return Name.Replace(" ", string.Empty) + ".jpg"; }
            }
        }
    }

As you can see I am using a calculated property to create an image name for each cake. I only need 1 image for each cake. Now when I go to Edit a cake on my CRUD pages. I would like to add a simple Image upload that will upload an image (No need for resizing or thumbnails) But I would like to impose the calculated property name. In other words: no matter what the user has named their photo, my upload code will rename it to whatever the Cakes.Name is (minus any spaces) +".jpg" and save it to "~Images/Cakes".

I am only requiring the upload to be on the actual Edit page, so the cake will already have been created at this point. All of the information needed for renaming the file should be available and easy to utilize from the Edit page. Below is my Edit page code:

Edit Page:

@model TastyCakes.Models.Cakes

<div class="row">
    <div class="large-12 columns">
    <hgroup class="title">
        <h1>Edit Cakes</h1>
    </hgroup>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <hr />
            @Html.ValidationSummary(true)
            @Html.HiddenFor(model => model.CakesID)

            <div class="medium-12 column">
                @Html.LabelFor(model => model.Name)
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>

            <div class="medium-12 column">
                @Html.LabelFor(model => model.Description)
                @Html.EditorFor(model => model.Description)
                @Html.ValidationMessageFor(model => model.Description)
            </div>

            <div class="medium-12 column">
                @Html.LabelFor(model => model.Price)
                @Html.EditorFor(model => model.Price)
                @Html.ValidationMessageFor(model => model.Price)
            </div>

            <div class="medium-12 column">
                <input type="submit" value="Save" class="tiny button" /> 
                @Html.ActionLink("Back to List", "Index", null, new { @class = "tiny button" })
            </div>
        </div>
    }

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
    </div>
</div>

I have reviewed a few html5 & ASP.Net 4 solutions, but this is too much. What I want is very simple. Any ideas or a kick in the right direction would be very much appreciated. I am using this code not only for a clients website but to include in a fictional website used to teach very basic MVC concepts.

解决方案

You'll need to:

Then add an HttpPostedFileBase to your model with the same name as the name of the input. Then the HttpPostedFileModelBinder will populate the model property from the uploaded file before the action is invoked. Note, I think you should probably add in the model id somewhere, perhaps as a path element, to guaranteed uniqueness in the image path so that images don't accidentally get overwritten.

There's a reasonably complete discussion of this at http://www.prideparrot.com/blog/archive/2012/8/uploading_and_returning_files

public class Cakes
{
    ...

    public HttpPostedFileBase UploadedFile { get; set; }

}

[HttpPost]
public ActionResult Edit(Cakes cake) // I'd probably use a view model here, not the domain model
{
      if (ModelState.IsValid)
      {
           if (cakes.UploadedFile != null)
           {
               cakes.UploadedFile.SaveAs(Path.Combine("path-to-images-for-this-cake", cakes.CakeImage));
           }

           ....
      }
}

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

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆