asp.net core 中的多个文件上传不起作用

问题描述 投票:0回答:2

我正在开发 .net core 3.1。我的问题是,当我尝试上传多个文件时,它只选择我最新上传的文件。对于 Egg,当我上传 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);
            }
c# file asp.net-core razor data-annotations
2个回答
0
投票

下面是获取文件的demo,大家可以参考一下。

多控制器:

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



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

索引

@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>

多个文件:

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

结果:


0
投票

[HttpPut("多文件上传")] 公共异步任务MultiFileUpload(IFormFileCollection集合文件,字符串产品代码) { APIResponse 响应 = new APIResponse(); int 通行数 = 0; int 错误计数 = 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 = $"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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.