ASP.NET Core中的多个文件上传不起作用

发布于 2025-01-30 15:36:01 字数 7057 浏览 3 评论 0原文

我正在研究.NET Core 3.1。我的问题是,当我尝试上传多个文件时,它仅选择我已上传的文件。对于鸡蛋,当我上传3个文件时,只有第三个文件进入控制器。

我的模型:

public class ProductModel
    {
        public int ProductId { get; set; }

        [Required(ErrorMessage ="Product Name is Required")]
        public string ProductName { get; set; }

        public string ProductDescription { get; set; }

        [Required(ErrorMessage ="Atleast one category need to be selected")]
        public int[] ProductCategoryIds { get; set; }

        public string Category { get; set; }

        [Required(ErrorMessage = "Product Needs to have any brand")]
        public int? BrandId { get; set; }

        public string BrandName { get; set; }

        [Required(ErrorMessage ="Tax is Required")]
        public int? TaxId { get; set; }

        public DateTime CreatedDate { get; set; }

        [Required(ErrorMessage ="Product Price is Required")]
        public decimal? ProductPrice { get; set; }

        public string ProductModels { get; set; }

        [Required(ErrorMessage ="Available quantity is Required")]
        public  int? AvailableQuantity { get; set; }

        public string StockStatus { get; set; }

        [Required(ErrorMessage = "Image is Required")]
        [ValidateFile(ErrorMessage ="Invalid File Type")]
        //[RegularExpression(@"([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.JPG|.PNG)$", ErrorMessage = "Invalid File types")]
        public IFormFile ProductImage { get; set; }

        public string ProductImagePath { get; set; }

        public List<IFormFile> AdditionalImages { get; set; }

        public bool IsActive { get; set; }

        public string ColorAttribute { get; set; }

        public int? DiscountProductCount1 { get; set; }
        public int? DiscountProductCount2 { get; set; }
        public int? DiscountProductCount3 { get; set; }

        public int[] AttributesId { get; set; }

        public string AttributesAsString { get; set; }

        public decimal? DiscountProductPrice1 { get; set; }
        public decimal? DiscountProductPrice2 { get; set; }
        public decimal? DiscountProductPrice3 { get; set; }

        public string DiscountJson { get; set; }

        public decimal? ProductPriceOffer { get; set; }

        public int? MinimumQuantity { get; set; }

        public List<ProductImageModel> ProductImageList { get; set; }

        public List<CategoryModel> CategoryList { get; set; }

        public TaxModel Tax { get; set; }

        public List<TaxModel> TaxList { get; set; }

        public List<AttributesModel> AttributesList { get; set; }

        public List<ProductDiscountModel> DiscountsList { get; set; }

        public string CreatedBy { get; set; }
    }

我的CSHTML:

 <form asp-action="NewProducts" asp-controller="Product" method="post" autocomplete="off" enctype="multipart/form-data">
 <div class="form-group col-md-6">
                  <label>Product Additional Image</label>
                   <input type="file" class="form-control" id="AdditionalImages" asp-for="Product.AdditionalImages" multiple 
                        placeholder="Product Additional Image">
                   
                </div>
</form>

我的控制器,当我仅提交最新文件时,将进入控制器:

public IActionResult NewProducts(ProductModel product)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    product.AttributesAsString = GetAttributesAsJson(product);
                    product.DiscountJson = GetDiscountsAsJson(product);
                    //saving general and category details of product
                    ProductModel results = _product.SaveProductGeneral(product);
                    product.ProductId = results.ProductId;
                    List<ProductImageModel> images= GetProductImages(product);
                    
                    //saving all images
                    //string allImagesJson = JsonConvert.SerializeObject(images);
                    foreach(var image in images)
                    {
                        _product.SaveProductImages(image);
                    }
                    
                    ViewData["SuccessFormMessage"] = "Created Successfully";
                    ViewData["ErrorFormMessage"] = string.Empty;
                    ModelState.Clear();
                }
                else
                {
                    ViewData["SuccessFormMessage"] = string.Empty;
                    ViewData["ErrorFormMessage"] = "Check all Required Fields";
                }

                ProductViewModel container = new ProductViewModel();
                container.Heading = new HeadingModel();
                container.Heading.MainHeading = "Product Management";
                container.Heading.SubHeading = "Addd new products for your store";
                ViewData["BrandDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_brand.GetAllBrandsByType("Active"), null, "brand");
                ViewData["TaxDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_tax.GetAllTaxesForDropDown("product"), null, "tax");
                ViewData["CategoryDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_category.GetCategoriesByStatus("Active").Where(x => x.Level == 1).ToList(), null, "category");
                ViewData["StatusDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_common.GetAllActiveStatus(), null, "status");
                ViewData["AttributesDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_attributes.GetAllAttributes(), null, "attributes");
                return View(container);
            }
            catch(Exception ex)
            {
                _common.SaveErrorLog(ex.ToString());
                ProductViewModel container = new ProductViewModel();
                container.Heading = new HeadingModel();
                container.Heading.MainHeading = "Product Management";
                container.Heading.SubHeading = "Addd new products for your store";
                ViewData["BrandDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_brand.GetAllBrandsByType("Active"), null, "brand");
                ViewData["TaxDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_tax.GetAllTaxesForDropDown(string.Empty), null, "tax");
                ViewData["CategoryDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_category.GetCategoriesByStatus("Active").Where(x => x.Level == 1).ToList(), null, "category");
                ViewData["StatusDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_common.GetAllActiveStatus(), null, "status");
                ViewData["AttributesDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_attributes.GetAllAttributes(), null, "attributes");
                ViewData["SuccessFormMessage"] = string.Empty;
                ViewData["ErrorFormMessage"] = "Something went wrong in our end";
                return View(container);
            }

I am working on .net core 3.1. My problem is when I try to upload multiple files it is picking only the file which I have uploaded latest. For egg, when I upload 3 files only the third file is coming into the controller.

My model:

public class ProductModel
    {
        public int ProductId { get; set; }

        [Required(ErrorMessage ="Product Name is Required")]
        public string ProductName { get; set; }

        public string ProductDescription { get; set; }

        [Required(ErrorMessage ="Atleast one category need to be selected")]
        public int[] ProductCategoryIds { get; set; }

        public string Category { get; set; }

        [Required(ErrorMessage = "Product Needs to have any brand")]
        public int? BrandId { get; set; }

        public string BrandName { get; set; }

        [Required(ErrorMessage ="Tax is Required")]
        public int? TaxId { get; set; }

        public DateTime CreatedDate { get; set; }

        [Required(ErrorMessage ="Product Price is Required")]
        public decimal? ProductPrice { get; set; }

        public string ProductModels { get; set; }

        [Required(ErrorMessage ="Available quantity is Required")]
        public  int? AvailableQuantity { get; set; }

        public string StockStatus { get; set; }

        [Required(ErrorMessage = "Image is Required")]
        [ValidateFile(ErrorMessage ="Invalid File Type")]
        //[RegularExpression(@"([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.JPG|.PNG)
quot;, ErrorMessage = "Invalid File types")]
        public IFormFile ProductImage { get; set; }

        public string ProductImagePath { get; set; }

        public List<IFormFile> AdditionalImages { get; set; }

        public bool IsActive { get; set; }

        public string ColorAttribute { get; set; }

        public int? DiscountProductCount1 { get; set; }
        public int? DiscountProductCount2 { get; set; }
        public int? DiscountProductCount3 { get; set; }

        public int[] AttributesId { get; set; }

        public string AttributesAsString { get; set; }

        public decimal? DiscountProductPrice1 { get; set; }
        public decimal? DiscountProductPrice2 { get; set; }
        public decimal? DiscountProductPrice3 { get; set; }

        public string DiscountJson { get; set; }

        public decimal? ProductPriceOffer { get; set; }

        public int? MinimumQuantity { get; set; }

        public List<ProductImageModel> ProductImageList { get; set; }

        public List<CategoryModel> CategoryList { get; set; }

        public TaxModel Tax { get; set; }

        public List<TaxModel> TaxList { get; set; }

        public List<AttributesModel> AttributesList { get; set; }

        public List<ProductDiscountModel> DiscountsList { get; set; }

        public string CreatedBy { get; set; }
    }

My cshtml:

 <form asp-action="NewProducts" asp-controller="Product" method="post" autocomplete="off" enctype="multipart/form-data">
 <div class="form-group col-md-6">
                  <label>Product Additional Image</label>
                   <input type="file" class="form-control" id="AdditionalImages" asp-for="Product.AdditionalImages" multiple 
                        placeholder="Product Additional Image">
                   
                </div>
</form>

My controller, when I submits only the latest file is coming into the controller:

public IActionResult NewProducts(ProductModel product)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    product.AttributesAsString = GetAttributesAsJson(product);
                    product.DiscountJson = GetDiscountsAsJson(product);
                    //saving general and category details of product
                    ProductModel results = _product.SaveProductGeneral(product);
                    product.ProductId = results.ProductId;
                    List<ProductImageModel> images= GetProductImages(product);
                    
                    //saving all images
                    //string allImagesJson = JsonConvert.SerializeObject(images);
                    foreach(var image in images)
                    {
                        _product.SaveProductImages(image);
                    }
                    
                    ViewData["SuccessFormMessage"] = "Created Successfully";
                    ViewData["ErrorFormMessage"] = string.Empty;
                    ModelState.Clear();
                }
                else
                {
                    ViewData["SuccessFormMessage"] = string.Empty;
                    ViewData["ErrorFormMessage"] = "Check all Required Fields";
                }

                ProductViewModel container = new ProductViewModel();
                container.Heading = new HeadingModel();
                container.Heading.MainHeading = "Product Management";
                container.Heading.SubHeading = "Addd new products for your store";
                ViewData["BrandDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_brand.GetAllBrandsByType("Active"), null, "brand");
                ViewData["TaxDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_tax.GetAllTaxesForDropDown("product"), null, "tax");
                ViewData["CategoryDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_category.GetCategoriesByStatus("Active").Where(x => x.Level == 1).ToList(), null, "category");
                ViewData["StatusDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_common.GetAllActiveStatus(), null, "status");
                ViewData["AttributesDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_attributes.GetAllAttributes(), null, "attributes");
                return View(container);
            }
            catch(Exception ex)
            {
                _common.SaveErrorLog(ex.ToString());
                ProductViewModel container = new ProductViewModel();
                container.Heading = new HeadingModel();
                container.Heading.MainHeading = "Product Management";
                container.Heading.SubHeading = "Addd new products for your store";
                ViewData["BrandDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_brand.GetAllBrandsByType("Active"), null, "brand");
                ViewData["TaxDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_tax.GetAllTaxesForDropDown(string.Empty), null, "tax");
                ViewData["CategoryDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_category.GetCategoriesByStatus("Active").Where(x => x.Level == 1).ToList(), null, "category");
                ViewData["StatusDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_common.GetAllActiveStatus(), null, "status");
                ViewData["AttributesDropDown"] = CommonUtils.CommonUtils.GetDropDownByType(_attributes.GetAllAttributes(), null, "attributes");
                ViewData["SuccessFormMessage"] = string.Empty;
                ViewData["ErrorFormMessage"] = "Something went wrong in our end";
                return View(container);
            }

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

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

发布评论

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

评论(2

梦幻的心爱 2025-02-06 15:36:01

以下是有关获取文件的演示,您可以参考它。

muticontroller:

public class MutiController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }



        [HttpPost]
        public IActionResult Index(MultipleFile multipleFile)
        {
            return View();
        }
    }

index

@model MultipleFile
    
     <form asp-action="Index"   enctype="multipart/form-data">
                 <div class="form-group">
                    <label asp-for="Photo" class="control-label"></label>
                    <input type="file"   asp-for="Photo" class="form-control"  multiple />
                    <span asp-validation-for="Photo" class="text-danger"></span>
                </div>
                 <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
                  </form>

tovers torys

 public class MultipleFile
    {
        [Key]
        public string Name { get; set; }
        public List<IFormFile> Photo { get; set; }
    }

”在此处输入图像描述”

Below is demo about getting files, you can refer to it.

MutiController:

public class MutiController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }



        [HttpPost]
        public IActionResult Index(MultipleFile multipleFile)
        {
            return View();
        }
    }

Index

@model MultipleFile
    
     <form asp-action="Index"   enctype="multipart/form-data">
                 <div class="form-group">
                    <label asp-for="Photo" class="control-label"></label>
                    <input type="file"   asp-for="Photo" class="form-control"  multiple />
                    <span asp-validation-for="Photo" class="text-danger"></span>
                </div>
                 <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
                  </form>

MultipleFile:

 public class MultipleFile
    {
        [Key]
        public string Name { get; set; }
        public List<IFormFile> Photo { get; set; }
    }

result:

enter image description here

忱杏 2025-02-06 15:36:01
    [HttpPut("MultiFileUpload")]
    public async Task<IActionResult> MultiFileUpload(IFormFileCollection collectionfile, string productcode)
    {
        APIResponse response = new APIResponse();
        int passcount = 0;
        int errorcount = 0;

        try
        {
            var filePath = GetFilePath(productcode);
            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }

            foreach (var file in collectionfile)
            {
                var ImagePath = filePath + "\\" + file.FileName;

                if (System.IO.File.Exists(ImagePath))
                {
                    System.IO.File.Delete(ImagePath);
                }
                using (Stream stream = System.IO.File.Create(ImagePath))
                {
                    await file.CopyToAsync(stream);
                    passcount++;
                }
            }

            // Set response properties for success
            response.ResponseCode = 200;
            response.Result = 
quot;Successfully uploaded {passcount} files.";
        }
        catch (Exception ex)
        {
            errorcount++;

            // Set response properties for error
            response.IsError = true;
            response.Error = new ApiResponseError
            {
                ErrorCode = "1001",
                ErrorDescription = "File upload failed.",
                SysErrorDescription = ex.Message // Add more details if needed
            };
            response.ResponseCode = 500;
        }

        return Ok(response);
    }
    [HttpPut("MultiFileUpload")]
    public async Task<IActionResult> MultiFileUpload(IFormFileCollection collectionfile, string productcode)
    {
        APIResponse response = new APIResponse();
        int passcount = 0;
        int errorcount = 0;

        try
        {
            var filePath = GetFilePath(productcode);
            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }

            foreach (var file in collectionfile)
            {
                var ImagePath = filePath + "\\" + file.FileName;

                if (System.IO.File.Exists(ImagePath))
                {
                    System.IO.File.Delete(ImagePath);
                }
                using (Stream stream = System.IO.File.Create(ImagePath))
                {
                    await file.CopyToAsync(stream);
                    passcount++;
                }
            }

            // Set response properties for success
            response.ResponseCode = 200;
            response.Result = 
quot;Successfully uploaded {passcount} files.";
        }
        catch (Exception ex)
        {
            errorcount++;

            // Set response properties for error
            response.IsError = true;
            response.Error = new ApiResponseError
            {
                ErrorCode = "1001",
                ErrorDescription = "File upload failed.",
                SysErrorDescription = ex.Message // Add more details if needed
            };
            response.ResponseCode = 500;
        }

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