locked
How to upload files (pdf & docs files) and display it in the view page RRS feed

  • Question

  • User-67916611 posted

    Hi! I am a student and started to use ASP.NET Core MVC in creating a web-application for my project in school. My project has a feature of uploading pdf and docs files in the system and be able to display the uploaded files in the view page. I am really stuck on this part and my project must be out very soon. Please help me to solve this problem.

    I have watched several video tutorials and even read some articles related to file uploading but can't apply it to my project because it doesn't provide displaying the uploaded file in the view page. I'm also confused on where to store the files whether it would be on the database or in the www.root.

    As a reference, I've used this solution that I got from tutorials and tried to apply it in my project.

    FileController:

    // Uploading a file to add a new document
            public IActionResult MultipleFiles(IEnumerable<IFormFile> files)
            {
                int i = 0;
                foreach (var file in files)
                {
                    using (var fileStream = new FileStream(Path.Combine(_dir, $"file{i++}.pdf"), FileMode.Create, FileAccess.Write))
                    {
                        file.CopyTo(fileStream);
                    }
                }
                return RedirectToAction("Index"); 
            }

    Create.cshtml

    <div>
        <p> Upload files here </p>
        <form asp-controller="Home" asp-action="MultipleFiles"
              enctype="multipart/form-data" method="post">
            <input type="file" multiple name="files" />
            <button type="submit">Submit</button>
        </form>
    </div>

    The codes that I provided above doesn't work and I don't know what's the problem. I also don't have any codes for displaying the uploaded files to the view page.

    Please, Please help me on how to do it.

    Thank you for whatever help you may extend on this thread. :)

    Monday, September 2, 2019 1:38 PM

Answers

  • User711641945 posted

    Hi John,

    I am not clear your meaning.You said you have diplayed the file on the view page.But this url(https://localhost:44333/Users/GetPdf?fileName=sample.pdf) is used to display the file.If you display the file successfully,you would not make error.Did you use my entire code?

    For you want to download the displayed file,you could see download button in the upper right corner of view by default when you use google broswer(Microsoft Edge also works):

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 5, 2019 5:32 AM

All replies

  • User197322208 posted

    The codes that I provided above doesn't work

    How do you know that does not work ? Did you encounter any error ?

    Monday, September 2, 2019 3:11 PM
  • User-67916611 posted

    There's no error, its just that when you click the  submit button it will not return to the index page. Also you can't see the uploaded  file in the solution explorer.

    However, I just find out that I miss putting a asp-controller and asp-action to my <form></form> tag. Now, it seems that the uploading of files is working. Just don't know how could I display it in the view page. This is my code where I placed the asp-controller and asp-action.

    Create.cshtml

     <div>
                        <p> Upload files here... </p>
                        <form asp-controller="Document" asp-action="SingleFile" enctype="multipart/form-data" method="post">
                            <input type="file" multiple name="file" />
                            <div class="submit-holder"><input type="submit" value="Create" class="submit-edit" /></div>
                            <div>
                                <a asp-action="Index">Back to List</a>
                            </div>
                        </form>
                    </div>

    DocumentController

            public IActionResult SingleFile(IFormFile file)
            {
                using (var fileStream = new FileStream(Path.Combine(_dir, "sample.pdf"), FileMode.Create, FileAccess.Write))
                {
                    file.CopyTo(fileStream);
                }
                return RedirectToAction("Index");
            }
    

    Please help me on how could I display it in the view page. And also, please advice me or tell me if I'm correct in placing the files on the file stream, or do I have any option where I could store the uploaded files? Thank you very much!

    Tuesday, September 3, 2019 1:17 PM
  • User475983607 posted

    There's no error, its just that when you click the  submit button it will not return to the index page. Also you can't see the uploaded  file in the solution explorer.

    The ASP.NET core documentation explains how static files are handled in ASP.NET Core and how to list files from a directory.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.2

    Tuesday, September 3, 2019 2:56 PM
  • User711641945 posted

    Hi John,

    Here is a workaround as follow:

    1.You need to create a folder named 'file' in wwwroot. 

    2.Create a model:

    public class User
        {
            public int Id { get; set; }
            public string FileName { get; set; }
        }

    3.Create.cshtml is used to upload pdf file and make sure that the name of file should be ASCII(i.e. aaa.pdf) when you upload a file:

    @model User
    
    <div class="row">
        <div class="col-md-4">
            <form asp-action="Create" enctype="multipart/form-data">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="form-group">
                    <label asp-for="FileName" class="control-label"></label>
                    <input asp-for="FileName" type="file" name="file" id="file" class="form-control" />
                    <span asp-validation-for="FileName" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </form>
        </div>
    </div>

    4.Index.cshtml is used to display the file:

    @model IEnumerable<WebApplication4.Models.User>
    <p>
        <a asp-action="Create">Create New</a>
    </p>
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.FileName)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
    @foreach (var item in Model) {
            <tr>
                <td>
                    <p>@Html.ActionLink(item.FileName, "GetPdf", "Users", new { fileName = item.FileName }, null)</p>
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                </td>
            </tr>
    }
        </tbody>
    </table>
    

    4.Controller:

    private readonly WebApplication4Context _context;
    private IHostingEnvironment _env;
    
    public UsersController(WebApplication4Context context, IHostingEnvironment env)
    {
        _context = context;
        _env = env;
    }
    
    public async Task<IActionResult> Index()
    {
        return View(await _context.Users.ToListAsync());
    }
    public IActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public async Task<IActionResult> Create(IFormFile file, User user)
    {
        var fileName = System.IO.Path.GetFileName(file.FileName);
        var filePath = System.IO.Path.Combine(_env.WebRootPath, "file", fileName);
        if (file.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            user.FileName = fileName;
        }
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    [HttpGet]
    public ActionResult GetPdf(string fileName)
    {
        string filePath = "~/file/" + fileName;
        Response.Headers.Add("Content-Disposition", "inline; filename=" + fileName);
        return File(filePath, "application/pdf");
    }

    Best Regards,

    Rena

    Wednesday, September 4, 2019 1:54 PM
  • User-67916611 posted

    Hi rena :)

    Thanks for your help, I can now display the uploaded file to the view page. I appreciate that you have just solve my problem :)

    But there's another thing, how could the user download the displayed file for them to open and read the file? Sorry, just needed help on this. Thank you very much!

    When I click the displayed file in the view page, here's the error:

    This localhost page can’t be found

    No webpage was found for the web address: https://localhost:44333/Users/GetPdf?fileName=sample.pdf

    HTTP ERROR 404
    Wednesday, September 4, 2019 2:53 PM
  • User711641945 posted

    Hi John,

    I am not clear your meaning.You said you have diplayed the file on the view page.But this url(https://localhost:44333/Users/GetPdf?fileName=sample.pdf) is used to display the file.If you display the file successfully,you would not make error.Did you use my entire code?

    For you want to download the displayed file,you could see download button in the upper right corner of view by default when you use google broswer(Microsoft Edge also works):

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 5, 2019 5:32 AM
  • User-67916611 posted

    Hi Rena Ni,

    I use your entire code. I get the displayed file in the index page, but when you click the pdf file in the index page, it  will return to the error page like this https://localhost:44333/Users/GetPdf?fileName=sample.pdf

    Saturday, September 7, 2019 4:58 AM
  • User-67916611 posted

    Have you configure or add some codes in startup.cs or program.cs file?  

    Saturday, September 7, 2019 5:07 AM
  • User711641945 posted

    Hi John,

    I have not modify code in Startup.cs or program.cs. Be sure that your controller named UsersController.And I suggest that you could share your code that could reproduce your issue.

    Best Regards,

    Rena

    Monday, September 9, 2019 1:38 AM