c# - 上传图片asp.net Core

标签 c# asp.net asp.net-mvc razor

我是 ASP.net COre 的新手,我想上传一个文件(图像)并将其存储在特定的文件夹中。我一直在关注这个教程(File uploads in ASP.NET Core),但我不知道如何将它存储在刚刚上传到服务器上的文件中 这是 html :

<form method="post" enctype="multipart/form-data" asp-controller="UploadFiles" asp-action="Index">
<div class="form-group">
    <div class="col-md-10">
        <p>Upload one or more files using this form:</p>
        <input type="file" name="files" multiple />
    </div>
</div>
<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Upload" />
    </div>
</div>

这是 Controller

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);

// full path to file in temp location
var filePath = Path.GetTempFileName();

foreach (var formFile in files)
{
    if (formFile.Length > 0)
    {
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await formFile.CopyToAsync(stream);
        }
    }
}

// process uploaded files
// Don't rely on or trust the FileName property without validation.

return Ok(new { count = files.Count, size, filePath});
}

这是我正在使用的类

public interface IFormFile
{
string ContentType { get; }
string ContentDisposition { get; }
IHeaderDictionary Headers { get; }
long Length { get; }
string Name { get; }
string FileName { get; }
Stream OpenReadStream();
void CopyTo(Stream target);
Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);
}

我只需要将图像存储在像这样的文件夹中:C:\Users\DESKTOP-1603\Desktop\GestionSyndic\GestionSyndic\src\WebApplication1\wwwroot\images\ 并更改图像的名称谢谢 :D

最佳答案

通过简单的步骤在 ASP.NET Core MVC 中上传文件

1.Demo.cshtml 查看代码片段

<form method="post" enctype="multipart/form-data" asp-controller="Demo" asp-action="Index">
<div class="form-group">
    <div class="col-md-10">
        <p>Upload one or more files using this form:</p>
        <input type="file" name="files" multiple />
    </div>
</div>
<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Upload" />
    </div>
</div>

  1. 演示 Controller

为了展示演示,我创建了一个演示 Controller ,其中有 2 个操作方法,一个用于处理获取请求,另一个用于处理发布请求。

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Net.Http.Headers;

namespace WebApplication6.Controllers
{
    public class DemoController : Controller
    {
        private readonly IHostingEnvironment _environment;

        // Constructor
        public DemoController(IHostingEnvironment IHostingEnvironment)
        {
            _environment = IHostingEnvironment;
        }

        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(string name)
        {
            var newFileName = string.Empty;

            if (HttpContext.Request.Form.Files != null)
            {
                var fileName = string.Empty;
                string PathDB = string.Empty;

                var files = HttpContext.Request.Form.Files;

                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        //Getting FileName
                        fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                        //Assigning Unique Filename (Guid)
                        var myUniqueFileName = Convert.ToString(Guid.NewGuid());

                        //Getting file Extension
                        var FileExtension = Path.GetExtension(fileName);

                        // concating  FileName + FileExtension
                        newFileName = myUniqueFileName + FileExtension;

                        // Combines two strings into a path.
                        fileName = Path.Combine(_environment.WebRootPath, "demoImages") + $@"\{newFileName}";

                        // if you want to store path of folder in database
                        PathDB = "demoImages/" + newFileName;

                        using (FileStream fs = System.IO.File.Create(fileName))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }
                    }
                }


            }
            return View();
        }
    }
}

Snapshot while Debugging

Snapshot while Debuggin

Location of folder where Images are stored

Location of Folder where Images are Stored

关于c# - 上传图片asp.net Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47125439/

相关文章:

c# - 如何拉伸(stretch)图像以填充此 WPF/XAML 应用程序?

c# - 配置.MapODataServiceRoute 错误

c# - 局部 View 和布局有什么区别?

javascript - 如何在 JSON stringify 中使用特殊字符?

asp.net-mvc - Razor不会在HiddenFor中渲染隐藏的精确PK

c# - 无需 Controller 操作即可生成 View

c# - Sqlite设置序列化模式抛出异常

c# - 如何使用 SMO 在 C# 中迭代​​数据库对象

c# - 如何使用 asp.net 和 c# 从 Web 应用程序向手机发送短信?

c# - 添加到自定义 ActionLink 帮助程序扩展的 htmlAttributes