Asp.Net MVC 中的文件上传

发布于 2024-11-07 02:54:12 字数 702 浏览 0 评论 0原文

我正在尝试在我的 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-当我调试它时,它永远不会进入控制器。

I am trying to make a file uploading page in my MVC project. First of all i want to manage this locally.
My Questions are:
1- Here is my controller and view. Is there any thing that I have to do to make this code work? I mean defining a model or using jquery, etc. What is the process when a file is being uploaded?

[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();
}

Here is the View:

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

2- When i debug this, It never goes to controller.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花落人断肠 2024-11-14 02:54:12

您的视图表单上可能需要 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);
    }

其中有一些自定义位,因此您可以忽略它们。你需要的东西应该在那里。

华泰

You may need the enctype='multipart/form-data' on your view form:

    @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")
    }

And here is my controller code:

    [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);
    }

There are some custom bits in there so you can ignore those. The gyst of what you need should be there.

HTH

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文