有关foreach循环图像的问题

时间:2015-10-19 11:00:34

标签: asp.net-mvc

我正在尝试制作一个带有所有图像的foreach循环,当我调试代码时,我可以看到它需要图像核心但不是所有都是来到数据库。如果我选择3个图像,则数据库中只有2个,第三个只有路径,而不是图像。

有人可以帮助我。

以下是我的照片模型中的代码:

public class Photo
{
    public int PhotoId { get; set; }

    public String ProfileImagePath { get; set; }

    public int StudentId { get; set; }

    public virtual Student Student { get; set; }

    public void SaveImage(HttpPostedFileBase image,
        String serverPath, String pathToFile)
    {
        if (image == null) return;

        string filename = Guid.NewGuid().ToString();
        ImageModel.ResizeAndSave(
            serverPath + pathToFile, filename,
            image.InputStream, 200);

        ProfileImagePath = pathToFile + filename +
        ".jpg";
    }


}

这是我的控制器代码:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "StudentId,Name,Adress")] Student student,
        HttpPostedFileBase[] image)
    {
        if (ModelState.IsValid)
        {


            foreach (HttpPostedFileBase file in image)
            {

                string filePathToSave = "/ProfileImages/";
                photo.SaveImage(file, HttpContext.Server.MapPath("~"), "/ProfileImages/");
                photo = new Photo
                {
                    StudentId = student.StudentId,
                    Student = student,
                    ProfileImagePath = filePathToSave
                };
                 db.Photos.Add(photo);
            }
            db.Students.Add(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(student);
    }

1 个答案:

答案 0 :(得分:2)

您没有显示正确的代码(您显示的内容会引发异常)所以我假设您必须声明

Photo photo = new Photo();

photo.SaveImage(..)行之前的某个地方可能是错误的来源。此外,您的photo.SaveImage()设置ProfileImagePath的值(比如说.../ProfileImages/someGuid.jpg),但是当您致电/ProfileImages/时,您会覆盖它并将其替换为ProfileImagePath = filePathToSave

将代码更改为

var path = HttpContext.Server.MapPath("~/ProfileImages"); // only need to set this once
foreach (HttpPostedFileBase file in image)
{
    Photo photo = new Photo
    {
        StudentId = student.StudentId, // no need to set the Student property
    };
    photo.SaveImage(file, path); // this will set the ProfileImagePath property
    db.Photos.Add(photo);
}

SaveImage()方法

public void SaveImage(HttpPostedFileBase image, string path)
{
    if (image == null) return;
    string filename = string.Format("{0}.jpg", Guid.NewGuid());
    // not sure what the following line does to it may also need to be modified?
    ImageModel.ResizeAndSave(path, filename, image.InputStream, 200); 
    ProfileImagePath = Path.Combine(path, filename);
}

但是我会考虑将SaveImage()方法移出Photo类并进入单独的服务,特别是因为它似乎在另一个类中调用静态方法。