[HttpPost]
public async Task<IActionResult> Index(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath, "UploadedFiles/Archives");
foreach (var file in files)
{
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
return View();
}
我想将“校友调查.pdf”重命名为“2017.pdf”,我该怎么做? 另外我想限制用户只能上传.pdf文件,我应该搜索什么?
我想将“校友调查.pdf”重命名为“2017.pdf”,我该怎么做?
只是不要使用
file.FileName
并将其命名为您想要的任何名称。
[HttpPost]
public async Task<IActionResult> Index(ICollection<IFormFile> files) {
var uploads = Path.Combine(_environment.WebRootPath, "UploadedFiles/Archives");
foreach (var file in files) {
if (file.Length > 0) {
using (var fileStream = new FileStream(Path.Combine(uploads, "<My file name here>"), FileMode.Create)) {
await file.CopyToAsync(fileStream);
}
}
}
return View();
}
请注意,由于您有一组文件,因此在命名时需要考虑上传中的多个文件。无法将它们全部命名为相同。
我想限制用户只能上传.pdf文件,
对于文件限制,请使用文件输入标签中的
accept
属性 accept="application/pdf"
<input type="file"
class="form-control"
id="files"
name="files"
accept="application/pdf">
要重命名文件,请使用 Move,如下所示。对于oldFilePath和newFilePath,输入您之前的文件路径和要更改的新文件名的文件路径。
System.IO.File.Move(oldFilePath, newFilePath);
public IActionResult FileUpload()
{
try
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("Resources", "Files");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
//var fullPath = Path.Combine(pathToSave, fileName);
string renameFile = Convert.ToString(Guid.NewGuid()) + "." + fileName.Split('.').Last();
var fullPath = Path.Combine(pathToSave, renameFile);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok(new { renameFile });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error");
}
}`
您可以使用
Guid
为您的文件指定唯一的名称。这个独特的名字每次都不一样。
[HttpPost]
public async Task<IActionResult> Index(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath, "UploadedFiles/Archives");
foreach (var file in files)
{
if (file.Length > 0)
{
var uniqueFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
using (var fileStream = new FileStream(Path.Combine(uploads, uniqueFileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
return View();
}
并且将用户的文件输入限制为仅 pdf 在视图中:
<input type="file" name="files" id="files" class="form-control" accept="application/pdf" multiple />
虽然一年前就被问过,但我想贡献我的答案......这就是
[HttpPost]
public async Task<IActionResult> Index(IFormFile file)
{
if (file!= null && file.Length > 0)
{
var FilePath = Path.Combine(_environment.WebRootPath, "UploadedFiles/Archives/", "2017" + ".pdf" );
using (var stream = System.IO.File.Create(FilePath))
{
await file.CopyToAsync(stream);
}
}
return View();
}