[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();
}
它使用用户定义的名称保存文件。比如“Alumni Survey.pdf”
我想将“Alumni Survey.pdf”重命名为“2017.pdf”,我该怎么做? 除了我想限制用户只能上传.pdf文件,我应该搜索什么?
答案 0 :(得分:1)
我想将“Alumni Survey.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">
答案 1 :(得分:0)
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");
}
}`
答案 2 :(得分:0)
使用移动重命名文件,如下所示。对于 oldFilePath 和 newFilePath ,输入你之前的文件路径和要更改的新文件名的文件路径。
System.IO.File.Move(oldFilePath, newFilePath);