我是ASP.net CORE的新手,我想上传一个文件(图像)并将其存储在一个独立的文件夹中。我一直在关注这个tuto https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads,但我不知道如何将它存储在一个刚刚上传到服务器上的文件中 这是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>
这是控制器
[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
答案 0 :(得分:7)
在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>
为了展示演示,我创建了一个演示控制器,其中有2个动作方法,一个处理Get请求,另一个处理发布请求。
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();
}
}
}
调试时快照
存储图像的文件夹的位置
答案 1 :(得分:4)
您应该注入IHostingEnvironment
,以便获取网络根目录(默认情况下为wwwroot
)。
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
[HttpPost]
public async Task<IActionResult> UploadFiles(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)
{
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "images");
var fullPath = Path.Combine(uploads, GetUniqueFileName(formFile.FileName));
formFile.CopyTo(new FileStream(fullPath, FileMode.Create));
}
return Ok(new { count = files.Count, size, filePath });
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
这会将文件保存到images
中的wwwroot
目录。
确保您的表单标记的action
属性设置为HomeController的UploadFiles
操作方法(/Home/UploadFiles
)
<form method="post" enctype="multipart/form-data" asp-controller="Home"
asp-action="UploadFiles">
<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>
</form>
我不太确定你为什么要从这返回Ok结果。您可能会将重定向结果返回到列表页面。
答案 2 :(得分:0)
只是使用了@Saineshwar接受的答案,但做了一些重构作为一种扩展方法,以使其易于使用IFromFile
public static string MakeFileUniqueName(this IFormFile formFile)
{
if (formFile.Length > 0)
{
string fileName =
ContentDispositionHeaderValue.Parse(formFile.ContentDisposition).FileName.Trim('"');
// concatinating FileName + FileExtension
return Guid.NewGuid() + Path.GetExtension(fileName);
}
return string.Empty;
}