简体   繁体   English

如何将文件保存到 ASP.NET Core 中的另一个文件夹

[英]How to save files to another folder in ASP.NET Core

I am trying to make an image-saving tactic.我正在尝试制定一种节省图像的策略。 It's simple, the user uploads some images and sends them to a folder on the server's computer.很简单,用户上传一些图像并将它们发送到服务器计算机上的文件夹中。

I took a code to save only one image from the user at a time and tried to make it work with multiple images.我使用代码一次只保存用户的一张图片,并尝试让它与多张图片一起使用。 Here are the results:结果如下:

  • It still saves only one image.它仍然只保存一张图像。
  • The image is being saved as a HEX code.图像被保存为十六进制代码。

Here's the code:这是代码:

UploadModel.cs:上传模型.cs:

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SaveImagesTest.Models
{
    public class UploadModel
    {
        public List<string> Name { get; set; }
        public List<IFormFile> File { get; set; }
    }
}

FileUploadController:文件上传控制器:

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SaveImagesTest.Models;
using Microsoft.AspNetCore.Hosting;
using System.IO;

namespace SaveImagesTest.Controllers
{
    public class FileUploadController : Controller
    {
        [Obsolete]
        private IHostingEnvironment hostingEnv;

        [Obsolete]
        public FileUploadController(IHostingEnvironment env)
        {
            this.hostingEnv = env;
        }

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

        [HttpPost]
        [Obsolete]
        public IActionResult Upload(UploadModel upload)
        {
            var FileDic = "Files";

            string FilePath = Path.Combine(hostingEnv.WebRootPath, FileDic);

            if (!Directory.Exists(FilePath))
                Directory.CreateDirectory(FilePath);

            int count = 0;

            foreach (var file in upload.File)
            {
                
                var fileName = ++count;
                var filePath = Path.Combine(FilePath, fileName.ToString());

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

            return View("Index");
        }
    }
}

index.cshtml:索引.cshtml:

@model SaveImagesTest.Models.UploadModel

@{
     Layout = null;
}

<!DOCTYPE html>
<html>
<head>
     <meta name="viewport" content="width=device-width" />
     <title>ASP.NET Core save image to folder </title>
</head>
<body>
     @using (Html.BeginForm("Upload", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
     {
         <table>
             <tr>
                 <td>File Upload:</td>
                 <td>
                     <input type="file" id="File_Upload" name="File" onchange="readURL(this);" accept="image/*" multiple />
                     <br />
                 </td>
             </tr>
             <tr>
                 <td>File Name:</td>
                 <td>
                     @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                     @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                 </td>
             </tr>
             <tr>
                 <td></td>
                 <td>
                     <input type="submit" value="Upload" class="btn-default" />
                 </td>
             </tr>
         </table>
     }
 </body>
 </html>

Here's a short summary of what happens: I upload multiple random files, and I see that all of the images are there in the images list.以下是所发生情况的简短摘要:我上传了多个随机文件,我看到所有图像都在图像列表中。 in the Upload function, it's going but saves only the first as HEX.在 Upload function 中,它正在运行,但仅将第一个保存为 HEX。

how the image's being saved图像的保存方式

Using original a file name使用原始文件名

Try to use file name provided by the IFormFile :尝试使用IFormFile提供的文件名:

[HttpPost]
[Obsolete]
public IActionResult Upload(UploadModel upload)
{
    var FileDic = "Files";

    string FilePath = Path.Combine(hostingEnv.WebRootPath, FileDic);

    if (!Directory.Exists(FilePath))
        Directory.CreateDirectory(FilePath);
    
    foreach (var file in upload.File)
    {              
        var filePath = Path.Combine(FilePath, file.FileName);

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

    return View("Index");
}

Because of the IFormFile contains file name with the file extension, you will not have problem with opening these.由于IFormFile包含带有文件扩展名的文件名,因此打开这些文件不会有问题。

Using serial numbers for a file name使用序列号作为文件名

If you want to use serial numbers for file name then it's necessary to extract the file extension form the file name provided by the IFormFile interface:如果要使用序列号作为文件名,则需要从IFormFile接口提供的文件名中提取文件扩展名:

[HttpPost]
public IActionResult Upload(UploadModel upload)
{
    var FileDic = "Files";

    string FilePath = Path.Combine(hostingEnv.WebRootPath, FileDic);

    if (!Directory.Exists(FilePath))
        Directory.CreateDirectory(FilePath);

    int count = 0;
    foreach (var file in upload.File)
    {
        var extension = Path.GetExtension(file.FileName);
        var filePath = Path.Combine(FilePath, (++count).ToString()+extension);

        using (FileStream fs = System.IO.File.Create(filePath))
        {
            file.CopyTo(fs);
            continue;
        }
    }
    return View("Index");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET CORE,如何读取另一个进程使用的文件夹中的所有文件 - ASP.NET CORE, How read all files in a folder that is used from another process 我如何将文件保存在asp.net中Application文件夹外部IIS的文件夹中 - How can i save files in folder within the IIS of outside of the Application folder in asp.net 如何将图像保存在 ASP.NET Core MVC 中的文件夹中,该 MVC 来自 Xamarin.Forms ZE84ZDB60B939084CDB69 - How to save an image in a folder in ASP.NET Core MVC that comes from Xamarin.Forms Android? ASP.NET内核如何上传文件? - How to upload files in ASP.NET Core? 在数据库 ASP.NET Core 3.1 应用程序中保存和上传文件 - Save and upload files in database ASP.NET Core 3.1 application 将文件从 ASP.NET Core web api 发布到另一个 ASP.NET Core web api - Post files from ASP.NET Core web api to another ASP.NET Core web api 如何使用具有凭据的网络共享路径作为 asp.net 核心中的 static 文件夹 - How to use network shared path with credentials as static files folder in asp.net core 谁能告诉我如何将物理文件保存到配置提供的路径 - ASP.NET Core MVC - Can Anyone Show Me How to Save Physical Files to a Path Provided by Configuration - ASP.NET Core MVC 如何从一个表中获取 Id 并将其保存到 ASP.NET Core 中的另一个表,存储库模式 - How to get an Id from one table and save it to another table in ASP.NET Core, repository pattern 如何在asp.net core中设置linux nlog文件夹 - How to set linux nlog folder in asp.net core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM