Jessica
Jessica

Reputation: 23

How to rename uploaded files asp.net core mvc

i had created an upload link like this enter image description here Here was my code in the controller

    [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();
    }

it save the files inside with the name user defined. like the "Alumni Survey.pdf"enter image description here

i want to rename the "Alumni Survey.pdf" to "2017.pdf" how can i do that? besides i want to limit the user only can upload .pdf files, what should i search for it?

Upvotes: 2

Views: 9962

Answers (5)

om prakash
om prakash

Reputation: 29

Although its been asked a year ago, i would like to contribute my answer.... and here it is

[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();
    }

Upvotes: 0

Shah
Shah

Reputation: 9

You can use Guid to give your file a unique name. This unique name is different every time.

     [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();
}

And for limiting the user's file input to pdfs only In View:

<input type="file" name="files" id="files" class="form-control" accept="application/pdf" multiple />

Upvotes: 0

Mifdha Milan
Mifdha Milan

Reputation: 397

to rename the file use Move as given below. For oldFilePath and newFilePath put your previous file path and the file path with the new file name to be changed.

 System.IO.File.Move(oldFilePath, newFilePath);

Upvotes: 2

Rokive
Rokive

Reputation: 825

    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");
        }
    }`

enter image description here

Upvotes: 1

Nkosi
Nkosi

Reputation: 247018

i want to rename the "Alumni Survey.pdf" to "2017.pdf" how can i do that?

Just do not use the file.FileName and name it what ever you want.

[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();
}

Do note that as you have a collection of files you will need to cater for multiple files in the upload when naming them. Can't name them all the same.

i want to limit the user only can upload .pdf files,

for the file limitation use the accept attribute in the file input tag accept="application/pdf"

<input type="file" 
       class="form-control" 
       id="files" 
       name="files"
       accept="application/pdf">

Upvotes: 3

Related Questions