Загрузка файлов в asp.net MVC 2.0 - PullRequest
0 голосов
/ 17 марта 2012

Я занимаюсь разработкой приложения в asp.net mvc, в котором я хочу загрузить файл, и я использовал rendercontrol для рендеринга загрузчика файлов. В связи с этим я использую следующий код

<%: Html.RenderControl(new ControlInfo ()
                                                                {
                                                                    ControlID = item.ProjAttID,
                                                                    DefaultValue = item.DefaultValue,
                                                                    CanNull = item.CanNull, 
                                                                    // This field can be null. So, if field is null then don't pick the value of expression
                                                                    // from Regular Expression table. 
                                                                    RegularExpression = (item.RegularExpression != null)?  item.RegularExpression1.Value: null,
                                                                    ErrorMessage = (item.RegularExpression != null) ? item.RegularExpression1.Error : "",
                                                                    Type = (ControlType)item.FieldType,
                                                                    Value = (TempData["__" + item.ProjAttID] != null)? TempData["__" + item.ProjAttID].ToString() : null,
                                                                    ControlAttName = item.ProjAttName,
                                                                    RegExpressionID = (item.RegularExpression != null) ? item.RegularExpression1.ExpressionID : -1
                                                                }, true
                                                             )
                                    %>

и в своем контроллере я использую следующий код для сохранения файла

int i = new Random().Next();
            string fileName = i + Path.GetFileName(data[3]);

            fileName = fileName.Replace(" ", "-");

            string trailingPath = Path.GetFileName(fileName);
            string fullPath = Path.Combine(Server.MapPath("~/UploadedImages/"), trailingPath);
            ____.SaveAs(fullPath);

Я получаю имя файла, но сейчас не могу понять, как мне сохранить этот файл. Какой код я могу написать " _ .SaveAs (fullPath)" в этом месте " _ ", чтобы я мог сохранить свой файл. Пожалуйста, помогите мне

Привет

Мой контрольный помощник

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using UserInterface.Models;
using System.Web.Mvc;
using System.Text;

namespace UserInterface.HtmlHelpers
{
    // This enum defines the control types.
    public enum ControlType
    {
        TextField = 1,
        Password = 2,
        TextArea = 3,
        List = 4,
        CheckBox = 5,
        //06-03-2012
        UploadField = 6
        //
    }

    public static class ControlRenderHelper
    {
        public static MvcHtmlString RenderControl(this HtmlHelper html, ControlInfo pControlInfo, bool pSaveInfo, int pListSetID = 1)
        {
            string scriptString = "";
            MvcHtmlString controlString = MvcHtmlString.Create("");
            Dictionary<string, string> attributes = new Dictionary<string, string>();
            TagBuilder tag;

            if (pControlInfo.RegExpressionID == 6)
            {
                // Adding jquery code to show datepicker widget
                scriptString = "<script>$(function() { $('#_" + pControlInfo.ControlID + "').datepicker({ dateFormat: 'dd MM yy' });});</script>";
            }

            switch (pControlInfo.Type)
            {
                case ControlType.TextField:

                    tag = new TagBuilder("input");

                    // Tag attributes.
                    attributes.Add("type", "text");
                    attributes.Add("id", "_" + pControlInfo.ControlID);
                    attributes.Add("name", "_" + pControlInfo.ControlID);

                    // For client side validation (using Jquery).
                    if (!pControlInfo.CanNull)
                    {
                        attributes.Add("class", "required");
                    }

                    if (pControlInfo.Value != null)
                    {
                        attributes.Add("value", pControlInfo.Value);
                    }

                    else
                    {
                        attributes.Add("value", pControlInfo.DefaultValue);
                    }

                    tag.MergeAttributes(attributes);

                    // For client side validation.
                    scriptString += GetValidationScript(pControlInfo.ControlID, pControlInfo.RegularExpression, pControlInfo.ErrorMessage);
                    controlString = MvcHtmlString.Create(tag.ToString() + scriptString);

                    break;

                case ControlType.CheckBox:

                    tag = new TagBuilder("input");

                    // Tag attributes.
                    attributes.Add("type", "checkbox");
                    attributes.Add("id", "_" + pControlInfo.ControlID);
                    attributes.Add("name", "_" + pControlInfo.ControlID);
                    attributes.Add("value", "Yes");
                    if (pControlInfo.Value == "Yes")
                    {
                        attributes.Add("checked", "yes");
                    }

                    tag.MergeAttributes(attributes);
                    tag.InnerHtml = "  " + pControlInfo.ControlAttName;
                    controlString = MvcHtmlString.Create(tag.ToString());

                    break;

                case ControlType.TextArea:

                    tag = new TagBuilder("textarea");

                    // Tag attributes.
                    attributes.Add("rows", "4");
                    attributes.Add("cols", "40");
                    attributes.Add("id", "_" + pControlInfo.ControlID);
                    attributes.Add("name", "_" + pControlInfo.ControlID);

                    // For client side validation (using Jquery).
                    if (!pControlInfo.CanNull)
                    {
                        attributes.Add("class", "required");
                    }

                    tag.MergeAttributes(attributes);

                    if (pControlInfo.Value != null)
                    {
                        tag.InnerHtml = pControlInfo.Value;
                    }

                    else
                    {
                        tag.InnerHtml = pControlInfo.DefaultValue;
                    }

                    scriptString += GetValidationScript(pControlInfo.ControlID, pControlInfo.RegularExpression, pControlInfo.ErrorMessage);
                    controlString = MvcHtmlString.Create(tag.ToString() + scriptString);

                    break;

                case ControlType.List:

                    tag = new TagBuilder("select");
                    string[] options = pControlInfo.DefaultValue.Split(';');
                    string selectedValue = pControlInfo.Value;
                    StringBuilder temp = new StringBuilder();

                    // Tag attributes.
                    attributes.Add("id", "_" + pControlInfo.ControlID);
                    attributes.Add("name", "_" + pControlInfo.ControlID);
                    attributes.Add("class", "selectSize");
                    tag.MergeAttributes(attributes);

                    foreach (string val in options)
                    {
                        TagBuilder optionTag = new TagBuilder("option");
                        optionTag.InnerHtml = val;

                        if (val == selectedValue)
                        {
                            optionTag.MergeAttribute("selected", "selected");
                        }

                        temp.Append(optionTag.ToString());
                    }

                    tag.InnerHtml = temp.ToString();
                    controlString = MvcHtmlString.Create(tag.ToString());

                    break;

                case ControlType.Password:

                    tag = new TagBuilder("input");

                    // Tag attributes.
                    attributes.Add("type", "password");
                    attributes.Add("id", "_" + pControlInfo.ControlID);
                    attributes.Add("name", "_" + pControlInfo.ControlID);

                    // For client side validation (using Jquery).
                    if (!pControlInfo.CanNull)
                    {
                        attributes.Add("class", "required");
                    }

                    tag.MergeAttributes(attributes);

                    // For client side validation.
                    scriptString = GetValidationScript(pControlInfo.ControlID, pControlInfo.RegularExpression, pControlInfo.ErrorMessage);
                    controlString = MvcHtmlString.Create(tag.ToString() + scriptString);

                    break;

                case ControlType.UploadField:

                    tag = new TagBuilder("input");

                    // Tag attributes.
                    attributes.Add("type", "file");
                    attributes.Add("id", "_" + pControlInfo.ControlID);
                    attributes.Add("name", "_" + pControlInfo.ControlID);

                    // For client side validation (using Jquery).
                    if (!pControlInfo.CanNull)
                    {
                        attributes.Add("class", "required");
                    }

                    if (pControlInfo.Value != null)
                    {
                        attributes.Add("value", pControlInfo.Value);
                    }

                    else
                    {
                        attributes.Add("value", pControlInfo.DefaultValue);
                    }

                    tag.MergeAttributes(attributes);

                    // For client side validation.
                    scriptString += GetValidationScript(pControlInfo.ControlID, pControlInfo.RegularExpression, pControlInfo.ErrorMessage);
                    controlString = MvcHtmlString.Create(tag.ToString() + scriptString);

                    break;
            }

            if (pSaveInfo)
            {
                if (pListSetID == 1)
                {
                    // Please see the RenderedControlsInfo class to understand the purpose of following code snippet.
                    RenderedControlsInfo.L1ControlsID.Add(pControlInfo.ControlID);
                    RenderedControlsInfo.L1ControlsRegExpression.Add(pControlInfo.RegularExpression);
                    RenderedControlsInfo.L1ControlsCanNullProperty.Add(pControlInfo.CanNull);
                    RenderedControlsInfo.L1ControlsErrorMessage.Add(pControlInfo.ErrorMessage);
                }

                else
                {
                    RenderedControlsInfo.L2ControlsID.Add(pControlInfo.ControlID);
                    RenderedControlsInfo.L2ControlsRegExpression.Add(pControlInfo.RegularExpression);
                    RenderedControlsInfo.L2ControlsCanNullProperty.Add(pControlInfo.CanNull);
                    RenderedControlsInfo.L2ControlsErrorMessage.Add(pControlInfo.ErrorMessage);
                }
            }

            return controlString;
        }

        static string GetValidationScript(long pControlID, string pRegExp, string pErrorMessage)
        {
            string validationScript = null;

            if (pRegExp != null)
            {
                pRegExp = pRegExp.Replace("/", @"\/");
                // For client side validation.
                validationScript = "<script> $(function() {$.validator.addMethod('_" + pControlID + "', function(value, element) {" +
                                        "return this.optional(element) || /" + pRegExp + "/i.test(value); }, '" + pErrorMessage + "');$('#_" +
                                         pControlID + "').rules('add', '_" + pControlID + "');});</script>";

            }

            return validationScript;
        }
    }
}

Ответы [ 2 ]

1 голос
/ 17 марта 2012

Попробуйте это за основу, у меня это работает:

[View]

<% using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
   { %>
   <input type="file" name="file" />
   <input type="submit" value="upload" />
<% } %>

[Действия]

public ActionResult Upload()
{
    return View();
}

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    if (file != null)
    {
        file.SaveAs(Server.MapPath("~/App_Data/Uploads/" + file.FileName));
    }
    return View();
}

Важным для представления является то, что для формы необходимо задать тип enctype multipart / form-data. В действии параметр должен иметь то же имя, что и в форме.

0 голосов
/ 17 марта 2012

Вам нужно добавить HttpPostedFileBase к вашему действию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...