How to read a user-submitted txt file?

Asked

Viewed 1,184 times

0

I am learning Asp.net MVC and created a simple form:

<form>
    <div class="form-group">
        <label for="municipio">Nome do Município:</label>
        <input type="text" class="form-control" id="municipio" placeholder="Nome do Município">
    </div>
    <div class="form-group">
        <label for="arquivo">Selecionar arquivo...</label>
        <input type="file" id="arquivo">
        <p class="help-block">Selecione no seu computador o arquivo BPA</p>
    </div>
    <button type="submit" class="btn btn-default">Gerar relatório</button>
</form>

How do I read the file sent by the user and show the information on another page?

  • 1

    Would it not do to open in floating window? http://kithomepage.com//sos/How-to-a-txt-file-sent-by-user 2.htm

  • I am voting to close your question because there are several ways to do this. Besides, your question is not a specific problem, you ask us to do something.

  • @Leocaracciolo very good your idea . How to do?

  • @jbueno well that you could post some of the various ways you know. I don’t know any, so I created the post. But Edney helped me a lot ^^

  • 1

    @Italorodrigo is not the idea of the site.

  • 1

    I posted an answer with floating window

Show 1 more comment

2 answers

3


Hello, by posting this reply I am assuming that you are using ASP.NET MVC Core.

I created an extremely simple solution just so you can absorb some basic concepts.

First let’s create the Models Relatoriomunicipio and Municipality:

public class RelatorioMunicipio
{
    public RelatorioMunicipio(string caminhoBaseArquivo)
    {
        CaminhoBase = caminhoBaseArquivo;
    }
    public string CaminhoBase { get; set; }
    public Municipio Municipio { get; set; }

    public string AbrirArquivo()
    {
        return System.IO.File.ReadAllText(System.IO.Path.Combine(CaminhoBase, Municipio.Nome + ".txt"));
    }
}

using Microsoft.AspNetCore.Http;
public class Municipio
{
    public string Nome { get; set; }
    public IFormFile Arquivo{ get; set; }

}

Done this we will first change your view where you upload your file:

@model UploadArquivos.Model.Municipio

<form asp-action="GerarRelatorio" asp-controller="Home"  enctype="multipart/form-data">
    <div class="form-group">
        <label for="municipio">Nome do Município:</label>
        <input type="text" class="form-control" asp-for="Nome" as placeholder="Nome do Município">
    </div>
    <div class="form-group">
        <label for="arquivo">Selecionar arquivo...</label>
        <input type="file" asp-for="Arquivo">
        <p class="help-block">Selecione no seu computador o arquivo BPA</p>
    </div>
    <button type="submit" class="btn btn-default">Gerar relatório</button>
 </form>

In the example I created this view using the same Home and Index. Note that mark your form as enctype="Multipart/form-data", this serves to inform ASP.NET that its form will work with uploading files.

The instruction @model .... Municipio indicates that we are working with an object of this type passed by the action in your View, this makes it possible to use the commands Asp-for="Property Name", causing fields to be automatically mapped to properties in your post.

Now let’s go to the controllers: using Microsoft.AspNetCore.Mvc; using Uploadfiles.Model; using Microsoft.AspNetCore.Hosting; using System.IO; public class Homecontroller : Controller { Ihostingenvironment Enviroment { get; set; }

    public HomeController(IHostingEnvironment enviroment)
    {
        Enviroment = enviroment;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost] 
    [ValidateAntiForgeryToken]
    public IActionResult GerarRelatorio(Municipio municipio)
    {
        if (municipio.Arquivo != null)
        {
            // salvando arquivo em disco
            var reader = new BinaryReader(municipio.Arquivo.OpenReadStream());
            System.IO.File.WriteAllBytes(System.IO.Path.Combine(Enviroment.WebRootPath, $"{municipio.Nome}.txt"), reader.ReadBytes((int)municipio.Arquivo.Length));
        }
        return RedirectToAction("Exibir", "Relatorio", new { nome = municipio.Nome });
    }
}

At Home we need the Ihostingenvironment that is in namespace Microsoft.AspNetCore.Hosting, we only use it to get the root path of the application to save your file

In the Gerarreportario method notice that we have informed a parameter of the type Municipality, this is automatically assigned by the Framework when we perform the post due to what I said above.

Note that when we create your model Municipality in addition to the name we create a property of the type Iformfile Called File, it is in this property that ASP.NET will assign the posted file, and with it in hand save to disk with the Writeallbytes method.

This done we redirect to your Action Display in Controller Report informing the name of the municipality as a parameter.

And in the Report controller we have:

public class RelatorioController : Controller
{
    IHostingEnvironment Enviroment { get; set; }

    public RelatorioController(IHostingEnvironment enviroment)
    {
        Enviroment = enviroment;
    }

    [Route("Relatorio/Exibir/{nome}")]
    public IActionResult Exibir(string nome)
    {
        RelatorioMunicipio relatorio = new RelatorioMunicipio(Enviroment.WebRootPath);
        relatorio.Municipio = new Municipio() { Nome = nome };
        return View(relatorio);
    }
}

Here we just started an object of type Reporiomunicipio filling its properties. But as in Home, I need to inform the Webrootpath to inform the object where it should look for the file.

Finally we have the report View

@model UploadArquivos.Model.RelatorioMunicipio

<h1>@Model.Municipio.Nome</h1>

@Model.AbrirArquivo()

In it we simply inform the type of data that will be treated, display the name of the municipality and get the generated file.

For better understanding I published this project on Github, do the download and any doubt post in the comments.

I hope I’ve helped.

1

Library: you can pick up at github

<!DOCTYPE html>
<script language="javascript" src="/colorbox/jquery.min.js"></script> 
<script language="javascript" src="/colorbox/jquery.colorbox.js"></script>
<link rel="stylesheet" type="text/css" href="/colorbox/colorbox.css" media="screen" />
<style>#ajax{height:510px; width:640px;}</style>

Script

window.onload = function() {

    var arquivo = document.getElementById('arquivo');
    var fileDisplayArea = document.getElementById('fileDisplayArea');

    arquivo.addEventListener('change', function(e) {
        var file = arquivo.files[0];
        var textType = /text.*/;

        if (file.type.match(textType)) {
            var reader = new FileReader();

            reader.onload = function(e) {
                fileDisplayArea.innerText = reader.result;

            }
                $.colorbox({inline:true, href:".ajax"});
                reader.readAsText(file);    
        } else {
            fileDisplayArea.innerText = "File not supported!"
        }
    });
 }

HTML

<form>
<div class="form-group">
    <label for="municipio">Nome do Município:</label>
    <input type="text" class="form-control" id="municipio" placeholder="Nome do Município">
</div>
<div class="form-group">
    <label for="arquivo">Selecionar arquivo...</label>
    <input type="file" id="arquivo">
</div>
</form>
<div style='display:none'>
<div id='ajax' class='ajax'>
<div id='inline_content' style='padding:10px; background:#fff;'>
<div id='fileDisplayArea' class='div1'><div>
</div>
</div>

Browser other questions tagged

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