0
 [HttpPost("FilePost")]
    public async Task<IActionResult> FilePost(List<IFormFile> files)
    {
        long size  = files.Sum(f => f.Length);
        var filePath = Directory.GetCurrentDirectory() + "/files";
        if (!System.IO.Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }

        foreach (var item in files)
        {
            if (item.Length > 0)
            {
                using (var stream = new FileStream(filePath,FileMode.CreateNew))
                {
                    await item.CopyToAsync(stream);
                }
            }
        }
        return Ok(new { count = files.Count, size, filePath });

    }

FormFile. FileName = directory + filename,

Uploaded file, file name with path information, how to do?

I just need to get the name of the file.

whuanle
  • 69
  • 1
  • 7

3 Answers3

2

I just need to get the name of the file.

Use Path.GetFileName() to get the name of the file , and use Path.Combine() to combine the the save path you want with the file name , try the code like below

 var filesPath = Directory.GetCurrentDirectory() + "/files";
        if (!System.IO.Directory.Exists(filesPath))
        {
            Directory.CreateDirectory(filesPath);
        }

        foreach (var item in files)
        {
            if (item.Length > 0)
            {
                var fileName = Path.GetFileName(item.FileName);
                var filePath = Path.Combine(filesPath, fileName);
                using (var stream = new FileStream(filesPath, FileMode.CreateNew))
                {
                    await item.CopyToAsync(stream);
                }
            }
        }
Xueli Chen
  • 11,987
  • 3
  • 25
  • 36
  • I am glad to help you , could you mark my reply as an answer ?It will help others who have the same doubts to find the answer quickly . If you don't know how to mark the answer , pleaser refer to [here](https://stackoverflow.com/help/someone-answers) . Thanks a lot ! – Xueli Chen Apr 15 '19 at 01:53
  • There's a minor correction: you should construct the FileStream with filePath instead of filesPath – CodePro_NotYet Aug 17 '23 at 05:09
0

Seem like you want to get the file name base on your file path. You can get it into way

using System.IO;

Path.GetFileName(filePath);

or extension method

public static string GetFilename(this IFormFile file)
{
    return ContentDispositionHeaderValue.Parse(
                    file.ContentDisposition).FileName.ToString().Trim('"');
}

Please let me know if you need any help

0

I faced the same issue with different browsers. IE send FileName with full path and Chrome send only the file name. I used Path.GetFileName() to overcome issue.

Other fix is at your front end side. Refer this to solve from it front end side.

cdev
  • 5,043
  • 2
  • 33
  • 32