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.