簡體   English   中英

為什么我的文件沒有保存到我的 ASP.NET 核心應用程序中的指定目錄?

[英]Why are my files not saving to my specified directory in my ASP.NET Core Application?

我正在嘗試將文件保存到我的 ASp.NET Core 應用程序中的本地目錄,雖然還有其他更好的方法可以做到這一點,但這是用戶要求的方式。 所以,我在我的 controller 中設置了我的文件上傳,如下所示:

家庭控制器.cs

[HttpPost]
public IActionResult Create(CreateProductViewModel model)
{
    if (ModelState.IsValid && model !=null)
    {
        try
        {
            //Save the Product
            var product = new Products
            {
                Id = model.Products.Id,
                Title = model.Products.Title,
            };
            //Insert the product and get the newly created Id
            _productsService.InsertProduct(product);
            int newId = product.Id;

            //Process the Images
            if (model.Products.ProductImages != null)
            {
                try
                {                            
                    var root = _env.WebRootPath;
                    var images = model.Products.ProductImages;
                    var path = Path.Combine(root, "images", "products", newId.ToString());                            

                    foreach (var item in images) 
                    {
                        using (var stream = System.IO.File.Create(path))
                        {                                    
                            Stream inStream = item.OpenReadStream();
                            using Image image = Image.Load(inStream);
                            int width = 350;
                            int height = 0;
                            var clone = image.Clone(i => i.Resize(width, height));
                            clone.SaveAsJpeg(stream);                                
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        };
    }
    return RedirectToAction("Index", "Products");
}

這是代表此數據的 model

using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;

namespace MyProject.Data
{
    public class Products : BaseEntity
    {           
        public string Title { get; set; }  

        [NotMapped]
        public IFormFileCollection ProductImages { get; set; }
    }
}

發生了一些事情,過程需要如下

  • 產品已創建
  • 抓取新創建的產品 ID
  • 圖像路徑是使用新的產品 ID 創建的
  • 所有圖像都被迭代、處理並保存到新目錄中。

IE

  • wwwroot/images/products/54/imagefile01.jpg
  • wwwroot/images/products/54/imagefile02.jpg
  • wwwroot/images/products/54/imagefile03.jpg

但是,它並不是那樣工作的。 圖像未被保存,應用程序正在創建一個空文件(0 字節),名稱為產品 ID:

  • wwwroot/images/products/54

我做錯了什么,它沒有正確創建產品 ID,為什么它沒有將我的文件保存到該目錄中? 我覺得我錯過了一步。

path錯誤。 您將所有 iamges 保存到同一個目錄中,名稱相同。 由於該行using (var stream = System.IO.File.Create(path))

並且圖像高度為 0。您也必須更改它。

試試這個。

[HttpPost]
public IActionResult Create(CreateProductViewModel model)
{
    if (ModelState.IsValid && model !=null)
    {
        try
        {
            //Save the Product
            var product = new Products
            {
                Id = model.Products.Id,
                Title = model.Products.Title,
            };
            //Insert the product and get the newly created Id
            _productsService.InsertProduct(product);
            int newId = product.Id;

            //Process the Images
            if (model.Products.ProductImages != null)
            {
                try
                {                            
                    var root = _env.WebRootPath;
                    var images = model.Products.ProductImages;
                    var saveDirectory = Path.Combine(root, "images", "products", newId.ToString());                            

                    var iterator = 0;
                    foreach (var item in images) 
                    {
                        using (var stream = System.IO.File.Create(Path.Combine(saveDirectory, $"image{iterator++}.jpg")))
                        {                                    
                            Stream inStream = item.OpenReadStream();
                            using Image image = Image.Load(inStream);
                            int width = 350;
                            int height = WHY TIS IS ZERO?;
                            var clone = image.Clone(i => i.Resize(width, height));
                            clone.SaveAsJpeg(stream);                                
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        };
    }
    return RedirectToAction("Index", "Products");
}

沒有創建的文件夾不能直接讀取,也不需要每次都創建相同的文件路徑。

創建前請添加文件路徑是否存在的判斷。

並且不需要將創建路徑下的jpg轉成Stream格式來存儲上傳的圖片。 您可以直接使用clone.Save(filePath)方法將這些圖像以 jpeg 的形式保存。

請嘗試以下代碼。

[HttpPost]
        public IActionResult Create(ProductModel model)
        {
            if (ModelState.IsValid && model != null)
            {
                try
                {
                    //Save the Product
                    var product = new NewProducts
                    {
                        Id = model.Products.Id,
                        Title = model.Products.Title,
                    };
                    //Insert the product and get the newly created Id
                     _productsService.InsertProduct(product);
                    int newId = product.Id;

                    //Process the Images
                    if (model.Products.ProductImages != null)
                    {
                        try
                        {
                            var root = _env.WebRootPath;
                            var images = model.Products.ProductImages;
                            var path = Path.Combine(root, "images", "products", newId.ToString());
                            var iterator = 0;
                            foreach (var item in images)
                            {
                                var filePath = Path.Combine(path, $"imagefile0{iterator++}.jpg");
                                if (!Directory.Exists(path))
                                {
                                    Directory.CreateDirectory(path);
                                } 
                                Stream inStream = item.OpenReadStream();
                                using Image image = Image.Load(inStream);
                                int width = 350;
                                int height = 0;
                                var clone = image.Clone(i => i.Resize(width, height));
                                clone.Save(filePath); 
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                };
            }
            return RedirectToAction("Index", "Products");
        }

下面是調試過程和結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM