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

2

I would like to upload text files where I select N .txt files and save them to a directory I have specified in the application; I made an example that was on the internet but I 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");
    }

Template

    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" />



 }
    
asked by anonymous 30.03.2016 / 16:17

2 answers

1

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

The correct would be to get 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");
}
    
04.04.2017 / 16:40
0

I do generate TXT files 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);
    }
    
31.03.2016 / 14:28