ASP.NET Core Upload Multiple Files Simple Tutorial

2019年12月9日 3518点热度 2人点赞 2条评论
内容目录

 

Example source code download link

https://qcloud.coding.net/api/project/3915794/files/4463836/download

Project address:  https://dev.tencent.com/u/whuanle/p/asp.netcore_file_upload/attachment


 Create Application

Open VS 2017 

  --Create a new ASP.NET Core web application

    --Web Application (Model-View-Controller)  

Application name and path can be default


 

Remove Unnecessary Content

  • Open HomeController.cs file and delete all methods

 

 

  • Open Views/Home directory and delete all files

 

 

  • Create a new file directory in the application

 


 

Start Programming

Now, let's write the program to implement file upload

Step one  File upload interface

Create a new method in HomeController 

This action is the interface for uploading files

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

Then add a view Upload.cshtml in the Views/Home directory

Copy the following code into Upload.cshtml

This part is a file upload form, and there is nothing special about it, so no explanation of the code's function will be provided here.

@{
    ViewData["Title"] = "Upload";
}

<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="UploadFiles"> <div class="form-group"> <div class="col-md-12"> <p>Select the files to upload</p> <input type="file" name="files" multiple /> </div> </div> <div class="form-group"> <div class="col-md-12"> <input type="submit" value="Upload" /> </div> </div> </form>

 Annex

 


 

Step Two: File Upload Functionality

Open HomeController

The references at the top are as follows:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

  

 

Add a method inside the HomeController class

 

      [HttpPost]    // Uploading files is a post method, can add or omit here
        public async Task<IActionResult> UploadFiles(List<IFormFile> files)
        {
            long size = files.Sum(f => f.Length);       // Calculate the total size of all files
        <span style="color: #0000ff;">var</span> filepath = Directory.GetCurrentDirectory() + <span style="color: #800000;">"</span><span style="color: #800000;">\\file</span><span style="color: #800000;">"</span>;  <span style="color: #008000;">//</span><span style="color: #008000;"> Path to store files</span>
        ViewBag.log = <span style="color: #800000;">"</span><span style="color: #800000;">Log content is:</span><span style="color: #800000;">"</span>;     <span style="color: #008000;">//</span><span style="color: #008000;"> Record log content</span>

        <span style="color: #0000ff;">foreach</span> (<span style="color: #0000ff;">var</span> item <span style="color: #0000ff;">in</span> files)     <span style="color: #008000;">//</span><span style="color: #008000;"> Upload the selected file list</span>

{
if (item.Length > 0) // Only upload files larger than size 0
{
var thispath = filepath + "\" + item.FileName; // The current upload file should be stored here

                <span style="color: #0000ff;">if</span> (System.IO.File.Exists(thispath) == <span style="color: #0000ff;">true</span>)        <span style="color: #008000;">//</span><span style="color: #008000;"> If the file already exists, skip uploading this file</span>

{
ViewBag.log
+= "\r\nFile already exists:" + thispath.ToString();
continue;
}

                </span><span style="color: #008000;">//</span><span style="color: #008000;"> Upload file</span>
                <span style="color: #0000ff;">using</span> (<span style="color: #0000ff;">var</span> stream = <span style="color: #0000ff;">new</span> FileStream(thispath, FileMode.Create))      <span style="color: #008000;">//</span><span style="color: #008000;"> Create a file stream with a specific name</span>

{
try
{
await item.CopyToAsync(stream); // Upload file
}
catch (Exception ex) // Exception handling during upload
{
ViewBag.log
+= "\r\n" + ex.ToString();
}
}
}
}
return View();
}


Note: The usage of IFormFile will be introduced later

Here’s a structural diagram

Create a new view UploadFiles.cshtml in the Views/Home directory

Open UploadFiles.cshtml

Put the following code into it

The code below outputs the files in the file directory and displays the log record

@using System.IO
@{
    ViewData["Title"] = "UploadFiles";
}

<h2>Directory Content</h2> <ul class="list-group">  // Razor syntax to output files in the file directory @{ var items = Directory.GetFiles(Directory.GetCurrentDirectory() + "\file"); foreach (var item in items) { <li class="list-group-item">@item.ToString()</li> } } </ul> <hr /> <h2>Log Content</h2> <p> @ViewBag.log </p>


Run

Press F5 to run the application

Open 

https://localhost:your_port/Home/Upload

to see the running interface

 

Please select smaller document files such as txt, doc, pdf, images, etc. for testing; do not upload too many files

Do not choose too many or large files, dll files, executable files, etc. as it may cause errors


Upload Success

After a successful upload, you will be redirected to    https://localhost:your_port/Home/UploadFiles


Additional Notes

  • When uploading a duplicate file, the interface will prompt

 

  • Uploading files that are too large or too many will result in an error

  •  Usage of IFormFile

The namespace is  Microsoft.AspNetCore.Http

Properties 

ContentDisposition

Gets the raw Content-Disposition header of the uploaded file.

ContentType

Gets the raw Content-Type header of the uploaded file.

FileName

Gets the file name from the Content-Disposition header.


Headers

Gets the header dictionary of the uploaded file.

Length

Gets the length of the file in bytes.

Name

Gets the form field name from the Content-Disposition header.

Methods 

CopyTo(Stream)

Copies the content of the uploaded file to thetarget stream.

CopyToAsync(Stream, CancellationToken)

Asynchronously copies the content of the uploaded file to thetarget stream.

OpenReadStream()

Opens a request stream to read the uploaded file.

痴者工良

高级程序员劝退师

文章评论