如何上传文件并生成唯一的URL以在ASP.NET MVC中显示文件

时间:2017-08-18 06:45:13

标签: asp.net asp.net-mvc csv

我有工作代码上传CSV文件并在同一页面上查看它。我想在一个唯一的URL上查看每个文件。所以,像这样:

  1. 用户选择要上传的CSV文件
  2. 提交
  3. 重定向到一个唯一的URL(例如/ Index / 1234,其中1234是一个唯一的ID - 每个上传的文件都有一个唯一的ID,所以假设唯一的ID应该是“filename”或者其他东西)
  4. 在唯一网址上,显示文件内容
  5. 我还想要一个索引列表,其中显示每个上传的文件,然后用户可以选择要查看的文件。

    查看

                @using Read_CSV_MVC.Models
                @model IEnumerable<CustomerModel>
                @{
                    Layout = null;
                }
    
                <!DOCTYPE html>
    
                <html>
                <head>
                    <meta name="viewport" content="width=device-width" />
                    <title>Index</title>
                    <style type="text/css">
                        body {
                            font-family: Arial;
                            font-size: 10pt;
                        }
    
                        table {
                            border: 1px solid #ccc;
                            border-collapse: collapse;
                            background-color: #fff;
                        }
    
                            table th {
                                background-color: #B8DBFD;
                                color: #333;
                                font-weight: bold;
                            }
    
                            table th, table td {
                                padding: 5px;
                                border: 1px solid #ccc;
                            }
    
                            table, table table td {
                                border: 0px solid #ccc;
                            }
                    </style>
                </head>
                <body>
                    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
                    {
                        <input type="file" name="postedFile" />
                        <input type="submit" value="Import" />
                    }
                    @if (Model.Count() > 0)
                    {
                        <hr />
                        <table cellpadding="0" cellspacing="0">
                            <tr>
                                <th>Customer Id</th>
                                <th>Name</th>
                                <th>Country</th>
                            </tr>
                            @foreach (CustomerModel customer in Model)
                            {
                                <tr>
                                    <td>@customer.CustomerId</td>
                                    <td>@customer.Name</td>
                                    <td>@customer.Country</td>
                                </tr>
                            }
                        </table>
                    }
                </body>
                </html>
    

    控制器

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
            using System.Web.Mvc;
            using System.IO;
            using Read_CSV_MVC.Models;
    
            namespace Read_CSV_MVC.Controllers
            {
                public class HomeController : Controller
                {
                    // GET: Home
                    public ActionResult Index()
                    {
                        return View(new List<CustomerModel>());
                    }
    
                    [HttpPost]
                    public ActionResult Index(HttpPostedFileBase postedFile)
                    {
                        List<CustomerModel> customers = new List<CustomerModel>();
                        string filePath = string.Empty;
                        if (postedFile != null)
                        {
                            string path = Server.MapPath("~/Uploads/");
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
    
                            filePath = path + Path.GetFileName(postedFile.FileName);
                            string extension = Path.GetExtension(postedFile.FileName);
                            postedFile.SaveAs(filePath);
    
                            //Read the contents of CSV file.
                            string csvData = System.IO.File.ReadAllText(filePath);
    
                            //Execute a loop over the rows.
                            foreach (string row in csvData.Split('\n'))
                            {
                                if (!string.IsNullOrEmpty(row))
                                {
                                    customers.Add(new CustomerModel
                                    {
                                        CustomerId = Convert.ToInt32(row.Split(',')[0]),
                                        Name = row.Split(',')[1],
                                        Country = row.Split(',')[2]
                                    });
                                }
                            }
                        }
    
                        return View(customers);
                    }
                }
            }
    

    模型

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
    
            namespace Read_CSV_MVC.Models
            {
                public class CustomerModel
                {
                    ///<summary>
                    /// Gets or sets CustomerId.
                    ///</summary>
                    public int CustomerId { get; set; }
    
                    ///<summary>
                    /// Gets or sets Name.
                    ///</summary>
                    public string Name { get; set; }
    
                    ///<summary>
                    /// Gets or sets Country.
                    ///</summary>
                    public string Country { get; set; }
                }
            }
    

    感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:0)

控制器中的

需要更改

    public ActionResult Index(string id)
    {

        string path = Server.MapPath("~/Uploads/");
        var Files = Directory.GetFiles(path);
        List<CustomerModel> customers = new List<CustomerModel>();          
        if (!string.IsNullOrWhiteSpace(id) && Files.FirstOrDefault(x => x.Contains(id)) !=null)            {
            string filePath = Files.FirstOrDefault(x => x.Contains(id));
            string csvData = System.IO.File.ReadAllText(filePath);
            //Execute a loop over the rows.
            foreach (string row in csvData.Split('\n'))
            {
                if (!string.IsNullOrEmpty(row))
                {
                    customers.Add(new CustomerModel
                    {
                        CustomerId = Convert.ToInt32(row.Split(',')[0]),
                        Name = row.Split(',')[1],
                        Country = row.Split(',')[2]
                    });
                }
            }
        }
        ViewBag.files = Files.Select(x => x.Remove(x.LastIndexOf("."), x.Length - x.LastIndexOf(".")).Replace(path, "")).ToArray();
        return View(customers);
    }
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        List<CustomerModel> customers = new List<CustomerModel>();
            string path = Server.MapPath("~/Uploads/");
        string filePath = string.Empty;
        if (postedFile != null)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            filePath = Path.Combine(path, postedFile.FileName);
            postedFile.SaveAs(filePath);
            string csvData = System.IO.File.ReadAllText(filePath);
            //Execute a loop over the rows.
            foreach (string row in csvData.Split('\n'))
            {
                if (!string.IsNullOrEmpty(row))
                {
                    customers.Add(new CustomerModel
                    {
                        CustomerId = Convert.ToInt32(row.Split(',')[0]),
                        Name = row.Split(',')[1],
                        Country = row.Split(',')[2]
                    });
                }
            }
        }
        var Files = Directory.GetFiles(path);
        ViewBag.files = Files.Select(x => x.Remove(x.LastIndexOf("."), x.Length - x.LastIndexOf(".")).Replace(path, "")).ToArray();
        return View(customers);
    }

并在视图中将此div添加到body标记内。

 <div>
    @if (ViewBag.files !=null)
    {
        foreach (var item in (string[])ViewBag.files)
        {
            @Html.ActionLink(item, "index", new { id = item })                <br />
        }
    }
</div>

它会起作用

答案 1 :(得分:0)

Your Code has many issue but answer to your question is as follows:
You Can Replace File Name by a GUID or any you prefer.
if (ModelState.IsValid)
            {
                string _filename = string.Empty;
                if (file != null)
                {
                    _filename = SaveFile(file);
                }

                    cat.PictureName = _filename;

            }
            return View(cm);
        }
// save file Method
        private string SaveFile(HttpPostedFileBase file)
        {
                var fileName = Path.GetFileName(file.FileName);
                var _ext = Path.GetExtension(file.FileName);
                var sizeinKB = file.ContentLength / 1024;
// if you wnt to save path add path infornt of Guid.NewGuid() liKe
// string _filename = "~Images/Category/"+Guid.NewGuid().ToString();

               string _filename = Guid.NewGuid().ToString();
                var _comPath = HttpContext.Server.MapPath("~/Images/Category/")
                                                            + _filename + _ext;
                file.SaveAs(_comPath);
                MemoryStream ms = new MemoryStream();
                WebImage img = new WebImage(_comPath);
                if (img.Width > 2000 || img.Height> 2000)
                    img.Resize(2000, 2000);
                img.Save(_comPath);
                _filename = _filename  + _ext;
            return _filename;
        }