5

我对 ASP.net MVC 很陌生,所以请在你的回答中尽可能描述性:)

让我简化我正在尝试做的事情。想象一下,我有一个表格,您想在其中输入有关汽车的一些信息。这些字段可能是:品牌、型号、年份、Image1、Image2。

表格底部是一个“保存”按钮。关联的 Controller 方法会将 Image1 和 Image2 保存到磁盘,获取它们的文件名并将它们与汽车模​​型相关联,然后将它们保存到数据库中。

有任何想法吗?

多谢你们!

编辑

winob0t让我大部分时间都在那里。唯一突出的问题是:Image1 和 Image2 不是必填字段,所以我现在可以保存 0,1 或 2 张图像;但如果用户只上传 1 张图片,我无法知道它是来自 imageUpload1 还是 imageUpload2。

再次感谢任何帮助!

4

2 回答 2

7

在您的控制器中,您可以通过以下方式访问上传的文件:

    if(Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) {
        HttpPostedFileBase postFile = Request.Files.Get(0);
        string filename = GenerateUniqueFileName(postFile.FileName);
        postFile.SaveAs(server.MapPath(FileDirectoryPath + filename));
    }

protected virtual string GenerateUniqueFileName(string filename) {

    // get the extension
    string ext = Path.GetExtension(filename);
    string newFileName = "";

    // generate filename, until it's a unique filename
    bool unique = false;

    do {
        Random r = new Random();
        newFileName = Path.GetFileNameWithoutExtension(filename) + "_" + r.Next().ToString() + ext;
        unique = !File.Exists(FileDirectoryPath + newFileName);
    } while(!unique);
    return newFileName;
}

文本字段将像往常一样到达您的控制器操作,即 Request.Form[...]。请注意,您还需要将表单上的 enctype 设置为“multipart/form-data”。听起来您对 ASP.NET MVC 了解得足够多,可以完成剩下的工作。另请注意,您可以按如下方式在 aspx 视图中声明表单标记,但如果您愿意,可以使用更传统的方法。

<% using(Html.BeginForm<FooController>(c => c.Submit(), FormMethod.Post, new { enctype = "multipart/form-data", @id = formId, @class = "submitItem" })) { %> 

<% } %>
于 2009-03-03T00:58:25.160 回答
1

这是我的解决方案,上面的答案对我的情况不太适用。它不关心表单细节,并允许多次上传。

    for (int i = (Request.Files.Count - 1); i >= 0; i--)
    {
          if (Request.Files != null && Request.Files[i].ContentLength > 0)
          {
               string path = this.Server.MapPath("~/Content/images/");
               string filename = Path.GetFileName(Request.Files[i].FileName);
               string fullpath = Path.Combine(path, filename);
               Request.Files[i].SaveAs(fullpath);
           }
     }
于 2012-07-30T06:31:14.393 回答