【问题标题】:C#, ASP.NET MVC: Multiple image upload and uploaded images all remain the same problemC#, ASP.NET MVC:多张图片上传和上传图片都是一样的问题
【发布时间】:2020-11-23 19:41:31
【问题描述】:

我正在尝试上传多张图片,但我设法上传了我想要的尽可能多的图片。我唯一的问题是我选择的所有图像都复制了第一个图像。我在我的代码中找不到错误。

我的UploadImage 方法:

public static string UploadImage(string serverPath, IEnumerable<HttpPostedFileBase> files)
{
        Guid uniqueName = Guid.NewGuid(); 
        serverPath = serverPath.Replace("~", string.Empty);
        string filePath;

        foreach (HttpPostedFileBase item in files)
        {
            if (files != null && item.ContentLength > 0)
            {
                string extension = Path.GetExtension(item.FileName);
                string fileName = $"{uniqueName}{extension}";

                if (extension.ToLower() == ".jpeg" || extension.ToLower() == ".gif" || extension.ToLower() == ".png" || extension.ToLower() == ".jpg")
                {
                    if (File.Exists(HttpContext.Current.Server.MapPath(serverPath + fileName))) 
                    {
                        return "Already exists from same file";
                    }
                    else
                    {
                        filePath = Path.Combine(HttpContext.Current.Server.MapPath(serverPath),fileName);
                        item.SaveAs(filePath);
                        return serverPath+fileName;
                    }
                }
                else
                {
                    return "Not the selected picture.";
                }
            }
            else
            {
                return "No File Selected";
            }    
    }

    return "";
}

这是ImageController

[HttpPost]
public ActionResult Index(TestClass model, IEnumerable<HttpPostedFileBase> files)
{
        foreach (HttpPostedFileBase item in files)
        {
            model.ImagePath = ImageUploader.UploadImage("~/Images/", files) ;
            db.TestClass.Add(model);
            db.SaveChanges();
        }

        return View();
}

还有ImageClass

public class TestClass
{
    public int ID { get; set; }

    public string Name { get; set; }
    public string ImagePath { get; set; }
}

还有观点Index.cshtml

@using (Html.BeginForm("Index","Image",FormMethod.Post, new { enctype="multipart/form-data"}))
{
<div>
     Name
</div>
<div>
    @Html.TextBoxFor(x=>x.Name)
</div>
<div>
    <input multiple type="file" name="files" value="Browse" />
</div>
<div>
    <button class="btn btn-primary">Save</button>
</div>
}

【问题讨论】:

    标签: c# asp.net-mvc entity-framework


    【解决方案1】:

    您的问题是您只需生成一个唯一名称并将其用于所有名称。 你应该把这一行:

     Guid uniqueName = Guid.NewGuid(); 
    

    在你for循环中,像这样:

     foreach (HttpPostedFileBase item in files)
        {
            if (files != null && item.ContentLength > 0)
            {
                 Guid uniqueName = Guid.NewGuid(); 
                string extension = Path.GetExtension(item.FileName);
                string fileName = $"{uniqueName}{extension}";
               // the rest of your code
    }
    

    还有一些问题需要解决 1- 在您的操作方法中,您上传所有文件,但您的 UploadImage 方法只返回一个字符串,因此所有文件的 ImagePath 都是相等的。 你可以像下面这样重写它:

    foreach (HttpPostedFileBase item in files)
        {
            var  fileObj = new TestClass();
            fileObj.ImagePath = ImageUploader.UploadImage("~/Images/", files) ;
            db.TestClass.Add(fileObj);
            db.SaveChanges();
        }
    

    【讨论】:

    • 替换代码并没有帮助,而且这段代码也可以按照我想要的方式工作。当您将其添加到数据库时,名称会发生​​变化,但文件扩展名仍然是第一个选定文件的扩展名,并且所有图像都保持不变。
    • 您是否在for 循环中更改了Guid uniqueName = Guid.NewGuid();
    • 我还应该在foreach 循环内打开一个for 循环吗?
    【解决方案2】:

    感谢您的帮助,但编写这些代码并没有解决我的问题。 让我通过一个例子来解释这个问题; 例如,我选择了四张图片,当我单击保存按钮时,它会使用新的 Guid 名称添加到数据库中,但第一张所选照片的​​文件扩展名仍保留在内存中。图片文件夹中添加了四张图片,但图片都是一样的。

    enter image description here

    enter image description here

    【讨论】:

      【解决方案3】:

      已解决

      我意识到我尝试上传的照片一直被上传为同一张照片的原因是因为索引号总是被重置。

      作为解决方案: 我从 ImageUploader 静态方法中去掉了 foreach 循环,并为静态类定义了一个 int 类型变量,并且每次 ImageController 中的 foreach 循环运行时,它必然会运行在静态方法,每次递增一次。当我们想再次上传图像时,我们会在过程完成后将其归零,这样索引号就不会保持不变。当我们同时上传多张照片并将数据保存到数据库时,可以使用此解决方案。如果我们只想上传多张照片,应该使用 foreach 循环。

      public static class ImageUploader
      {
          internal static int indexer;
      
      
      public static string UploadImage(string serverPath, List<HttpPostedFileBase> files)
          {
              serverPath = serverPath.Replace("~", string.Empty);
              if (files != null || files[indexer].ContentLength < 0)
              {
                  Guid uniqueName = Guid.NewGuid();
                  string extension = Path.GetExtension(files[indexer].FileName);
                  string fileName = $"{uniqueName}{extension}";
                  if (extension.ToLower() == ".jpeg" || extension.ToLower() == ".gif" || extension.ToLower() == ".png" || extension.ToLower() == ".jpg")
                  {
                      if (File.Exists(HttpContext.Current.Server.MapPath(serverPath + fileName))) 
                      {
                          return "Already Exists From Same File";
                      }
                      else
                      {
                          string filePath = Path.Combine(HttpContext.Current.Server.MapPath(serverPath),fileName);
                          files[indexer].SaveAs(filePath);
                          indexer++;
                      if (indexer == files.Count)
                      {
                          indexer = 0;
                      }
                      return serverPath + fileName;
                      }
                  }
                  else
                  {
                      return "Not the selected picture.";
                  }
              }
              else
              {
                  return "No File Selected";
              }
          }
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-28
        • 1970-01-01
        • 2016-11-22
        • 1970-01-01
        • 2017-01-29
        相关资源
        最近更新 更多