无法验证和上传多张图片

时间:2018-11-08 16:34:16

标签: c# asp.net-mvc

我设法成功上传了一张图像,并且验证和上传过程正常进行,但是由于我尝试上传多张图像,因此没有验证或上传工作。

是称为“ ProductImage”的模型,它代表应该保存在磁盘和数据库中的“图像”对象。

public class ProductImage
{
public int ID { get; set; }
[Display(Name = "File")]
[StringLength(100)]
[Index(IsUnique = true)]
public string FileName { get; set; }
}
}

及其ProductImage的 controller (将接收的文件作为“ HttpPostedFileBase [] files”)通过它们,检查1-null和2-file的长度,如果它们是true,则检查使用ValidateFile()检查文件是否为jpeg,png和...并且小于2mb,如果文件有效,则将文件保存在磁盘中,然后继续将文件保存在数据库中,否则会引发错误消息。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Upload(HttpPostedFileBase[] files)
    {
        bool allValid = true;
        string inValidFiles = "";
        //check the user has entered a file
        if (files[0] != null)
        {
            //if the user has entered less than ten files
            if (files.Length <= 10)
            {
                //check they are all valid
                foreach (var file in files)
                {
                    if (!ValidateFile(file))
                    {
                        allValid = false;
                        inValidFiles += ", " + file.FileName;
                    }

                }
                //if they are all valid then try to save them to disk
                if (allValid)
                {
                    foreach (var file in files)
                    {
                        try
                        {
                            SaveFileToDisk(file);
                        }
                        catch (Exception)
                        {
                            ModelState.AddModelError("FileName", "Sorry ,and error has occured saving the file to disk,please try again.");
                        }

                    }
                }
                //else add an error listing out the invalid files
                else
                {
                    ModelState.AddModelError("FileName", "All files must be gif,png,jpeg or jpg and less than 2mb in size.The following files" + inValidFiles + "are not valid");
                }

            }
            //the user has entered more than 10 files
            else
            {
                ModelState.AddModelError("FileName", "Please only upload up to ten files at a time");
            }

        }
        //if the user has not entered a file return an error message
        else
        {
            ModelState.AddModelError("FileName", "Please choose a file");
        }

        if (ModelState.IsValid)
        {
            bool duplicates = false;
            bool otheDbError = false;
            string dublicatesFiles = "";
            foreach (var file in files)
            {
                //try and save each file
                var productToAdd = new ProductImage { FileName = file.FileName };
                try
                {
                    db.ProductImages.Add(productToAdd);
                    db.SaveChanges();
                }
                //if there is an exception check if it is caused by a duplicate file
                catch (DbUpdateException ex)
                {
                    SqlException innException = ex.InnerException.InnerException as SqlException;
                    if (innException != null && innException.Number == 2601)
                    {
                        dublicatesFiles += ", " + file.FileName;
                        duplicates = true;
                    }
                    else
                    {
                        otheDbError = true;
                    }
                }
            }
            //add a list of duplicate files to the error message
            if (duplicates)
            {

                ModelState.AddModelError("FileName", "All files uploaded except the files" + dublicatesFiles + "which already exist in the system." + "please delete them and try again if you wish to re-add them");
                return View();
            }
            else if (otheDbError)
            {
                ModelState.AddModelError("FileName","Sorry an error has occurred saving to the database ,please try again ");
                return View();
            }

        }

        return RedirectToAction("Index");
    }

这些是 helper方法:ValidateFile()和SaveFileToDisk()

private bool ValidateFile(HttpPostedFileBase file)
    {
        string FileExtension = System.IO.Path.GetExtension(file.FileName).ToLower();
        string[] allowedFileTypes = { ".gif", ".png", ".jpeg", "jpg" };
        if ((file.ContentLength > 0 && file.ContentLength < 2097152) && allowedFileTypes.Contains(FileExtension))
        {
            return true;
        }

        return false;
    }

    private void SaveFileToDisk(HttpPostedFileBase file)
    {
        WebImage img = new WebImage(file.InputStream);
        if (img.Width > 190)
        {
            img.Resize(190, img.Height);
        }

        img.Save(Constants.ProductImagePath + file.FileName);
        if (img.Width > 100)
        {
            img.Resize(100, img.Height);
        }

        img.Save(Constants.ProductThumbnailPath + file.FileName);
    }
}

}

并且我还更新了Upload.chtml页面中的“ multiple”属性,以允许更新一些文件

 <input type="file" name="files" id="files" multiple="multiple" class="form-control"/>

现在不管我做什么,上传正确或错误的文件,而不是显示错误消息或将其保存在databse或磁盘中,它只执行了最后一行代码

  return RedirectToAction("Index");

返回索引页面,出什么问题了?

0 个答案:

没有答案
相关问题