How to upload . txt file and save to a directory using c# net mvc?

Asked

Viewed 2,833 times

2

I would like to upload text files where I select N files. txt and saved in a directory I specified in the application; I made an example that was on the internet but could not get the files in my action.

Action:

 [HttpPost]
    public ActionResult Index(Upload upload)
    {
        foreach (var file in upload.Files) {
            if (file.ContentLength > 0)
            {
                var filename = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Arquivo"), filename);
                file.SaveAs(path);

        }

        }
        return RedirectToAction("Index");
    }

Model

    public class Upload
{
    public IEnumerable <HttpPostedFile> Files { get; set; }
}

View

      <h2>Upload de arquivo</h2>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
 { 

@Html.Label("File")
<input type="file" name="Files" id="Files" accept=".txt" multiple />
<input type="submit" value="Upload" />



 }
  • I recommend using this plugin, it is very good https://blueimp.github.io/jQuery-File-Upload/

2 answers

1

You are using a class that contains an enumerator of HttpPostedFile.


The correct thing would be for you to receive the files via HttpPostedFileBase.

[HttpPost]
public ActionResult Index(HttpPostedFileBase Files)
{
    // Verifica se o usuário selecionou algum arquivo
    if (Files != null && Files.ContentLength > 0)
    {
        // Extrai apenas o nome do arquivo
        var fileName = Path.GetFileName(Files.FileName);
        // Armazena o arquivo dentro da pasta ~/Arquivo
        var path = Path.Combine(Server.MapPath("~/Arquivo"), fileName);
        Files.SaveAs(path);
    }

    return RedirectToAction("Index");
}

0

I do TXT file generation this way:

    public FileResult DownloadFile(FileInfo file)
    {
        var extension = file.Extension;
        //Este é o content type utilizado para arquivos TXT  
        var contentType = "text/plain";
        //Em file.FullName está o caminho completo e nome do seu arquivo
        var stream = new FileStream(file.FullName, FileMode.Open);
        //Utilizando o FileMode.Open o arquivo será automaticamente gravado na pasta e baixado
        return File(stream, contentType, file.Name);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.