Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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:

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

how the image's being saved


1 Answers

Using original a file name

Try to use file name provided by the 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.

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:

[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");
}
like image 95
Victor Avatar answered Sep 06 '25 10:09

Victor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!