Загрузка файлов в Asp.Net MVC - PullRequest
0 голосов
/ 16 мая 2011

Я пытаюсь сделать страницу загрузки файла в моем проекте MVC.Прежде всего, я хочу управлять этим локально.Мои вопросы: 1- Вот мой контроллер и вид.Есть ли что-то, что я должен сделать, чтобы этот код работал?Я имею в виду определение модели или использование jquery и т. Д. Каков процесс загрузки файла?

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("C:/Users/marti/../PhotoGallery/myimages"),
                 Path.GetFileName(uploadFile.FileName));
                uploadFile.SaveAs(filePath);
            }
            return View();
}

Вот представление:

<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" />

2 - Когда я отлаживаюэто, он никогда не идет к контроллеру.

1 Ответ

0 голосов
/ 16 мая 2011

Вам может понадобиться enctype='multipart/form-data' в форме просмотра:

    @model ImageModel
    @{
        ViewBag.Title = "New Image";
    }
    <div class="content-form-container width-half">
        <form id='PropertiesForm' action='@Url.Action(ImageController.Actions.Add, ImageController.Name)' method='post' enctype='multipart/form-data' class='content-form'>
        @Html.Partial("ImageName")
        <fieldset class='content-form-1field'>
            <div class='legend'>
                file to upload
            </div>
            @Html.LabelledFileInput(ImageView.FileName, string.Empty)
        </fieldset>
        <div class='buttons'>
            @Html.Button("button-submit", "submit")
        </div>
        </form>
    </div>
    @section script{
        @Html.JavascriptInclude("~/js/image/new.min.js")
    }

А вот код моего контроллера:

    [HttpPost]
    [MemberAccess]
    public ActionResult Add()
    {
        var name = ImageView.ImageName.MapFrom(Request.Form);

        if (Request.Files.Count == 0)
        {
            RegisterFailureMessage("No file has been selected for upload.");

            return ValidationFailureAdd(name);
        }

        var file = Request.Files[0];

        if (file == null || file.ContentLength == 0)
        {
            RegisterFailureMessage("No file has been selected for upload or the file is empty.");

            return ValidationFailureAdd(name);
        }

        var format = ImageService.ImageFormat(file.InputStream);

        if (format != ImageFormat.Gif && format != ImageFormat.Jpeg && format != ImageFormat.Png)
        {
            RegisterFailureMessage("Only gif, jpg and png files are supported.");

            return ValidationFailureAdd(name);
        }

        if (query.HasName(name))
        {
            RegisterFailureMessage(string.Format("Image with name '{0}' already exists.", name));

            return ValidationFailureAdd(name);
        }

        using (var scope = new TransactionScope())
        {
            var id = Guid.NewGuid();

            var fileExtension = ImageService.FileExtension(format);

            Bus.Send(new AddWikiImageCommand
                     {
                         Id = id,
                         Name = name,
                         FileExtension = fileExtension
                     });

            var path = Path.Combine(ApplicationConfiguration.MediaFolder,
                                    string.Format("{0}.{1}", id.ToString("n"), fileExtension));

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }

            file.SaveAs(path);

            scope.Complete();
        }

        return RedirectToAction(Actions.Manage);
    }

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

HTH

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