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.

3 Answers 3

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);
                }
            }
        }
Sign up to request clarification or add additional context in comments.

2 Comments

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 . Thanks a lot !
There's a minor correction: you should construct the FileStream with filePath instead of filesPath
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.