ASP. NET Core file upload and download (multiple upload methods) and core File Upload

Source: Internet
Author: User

ASP. NET Core file upload and download (multiple upload methods) and core File Upload

Preface

Some time ago, the project went online, so it was too busy. Recently, I began to study ASP. NET Core.

I plan to write a series, but I haven't thought about the directory yet. Let's take a look at this article today. I will organize it later.

ASP. NET Core 2.0 has developed to the present and is very mature. Try to use it in the next project.

 

Body

1. Use model binding to upload files (Official example)

Address: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads

Let's talk about it here--, this TM machine translation... it's better to read E text by yourself ..

First, create a form as follows:

<Form method = "post" enctype = "multipart/form-data" asp-controller = "UpLoadFile" asp-action = "FileSave">

<Div>

<Div>

<P> Form multiple upload files: </p>

<Input type = "file" name = "files" multiple/>

<Input type = "submit" value = "Upload"/>

</Div>

</Div>

</Form>

Where,Asp-controllerAndAsp-action, (this is the TagHelper method, which will be discussed later)Is the controller and method we want to access.

Add the multiple attribute to the input tag to support Multifile upload.

To create a controller, write the upload method as follows:

Public async Task <IActionResult> FileSave (List <IFormFile> files)

{

Var files = Request. Form. Files;

Long size = files. Sum (f => f. Length );

String webRootPath = _ hostingEnvironment. WebRootPath;

String contentRootPath = _ hostingEnvironment. ContentRootPath;

Foreach (var formFile in files)

{

If (formFile. Length> 0)

{


String fileExt = GetFileExt (formFile. FileName); // file extension, excluding "."

Long fileSize = formFile. Length; // get the file size, in bytes

String newFileName = System. Guid. NewGuid (). ToString () + "." + fileExt; // a new file name is randomly generated.

Var filePath = webRootPath + "/upload/" + newFileName;

Using (var stream = new FileStream (filePath, FileMode. Create ))

{

Await formFile. CopyToAsync (stream );

}

}

}


Return OK (new {count = files. Count, size });

}

Here we use the new interface IFormFile of Asp. NET Core. The detailed definition of IFormFile is as follows:

Public interface IFormFile

{

String ContentType {get ;}

String ContentDisposition {get ;}

IHeaderDictionary Headers {get ;}

Long Length {get ;}

String Name {get ;}

String FileName {get ;}

Stream OpenReadStream ();

Void CopyTo (Stream target );

Task CopyToAsync (Stream target, CancellationToken cancellationToken = null );

}

The above Code uses IHostingEnvironment to obtain the root directory address of the project.

The constructor injection code is as follows:

Private readonly IHostingEnvironment _ hostingEnvironment;


Public UpLoadFileController (IHostingEnvironment hostingEnvironment)

{

_ HostingEnvironment = hostingEnvironment;

}

In this way, we have completed the preparation of the controller, and then to the running front-end, upload the file... the effect is as follows:

Through the CopyToAsync method of IFormFile, we can copy the file stream and save it locally.

 

2. Use Ajax to upload files

We used form upload, but in most cases, Ajax is used for upload during the project process. So let's talk about how to use Ajax for upload.

First, write the HTML code as follows:

<Div>

<Form id = "uploadForm">

Upload multiple files through AJAX: <input type = "file" name = "file" multiple/>

<Input type = "button" value = "Upload" onclick = "doUpload ()"/>

</Form>

</Div>

Compile the JS Code as follows (Here we use the FormData object to upload ):

Function doUpload (){

Var formData = new FormData ($ ("# uploadForm") [0]);

$. Ajax ({

Url: '@ Url. Action ("FileSave ")',

Type: 'post ',

Data: formData,

Async: false,

Cache: false,

ContentType: false,

ProcessData: false,

Success: function (returndata ){

Alert (returndata );

},

Error: function (returndata ){

Alert (returndata );

}

});

}

The background code is not modified. We will find thatList <IFormFile> filesFile cannot be obtained.

Through debugging, we can find that the file is uploaded successfully, but stored inRequest. Form. Files.

Therefore, modify the background Code as follows:

Public async Task <IActionResult> FileSave ()

{

Var date = Request;

Var files = Request. Form. Files;

Long size = files. Sum (f => f. Length );

String webRootPath = _ hostingEnvironment. WebRootPath;

String contentRootPath = _ hostingEnvironment. ContentRootPath;

Foreach (var formFile in files)

{

If (formFile. Length> 0)

{


String fileExt = GetFileExt (formFile. FileName); // file extension, excluding "."

Long fileSize = formFile. Length; // get the file size, in bytes

String newFileName = System. Guid. NewGuid (). ToString () + "." + fileExt; // a new file name is randomly generated.

Var filePath = webRootPath + "/upload/" + newFileName;

Using (var stream = new FileStream (filePath, FileMode. Create ))

{

Await formFile. CopyToAsync (stream );

}

}

}


Return OK (new {count = files. Count, size });

}

Change to direct fromRequest. Form. Files.~

 

3. Use webUploader to upload files

A long time ago, the JavaScript code of a webUploader was encapsulated as follows:

Second encapsulation of Baidu WebUploader's open-source upload control, streamlining the front-end code (two sentences of code to complete the upload)

Secondary encapsulation of Baidu WebUploader to streamline the image preview and upload of front-end code (two sentences of code can be uploaded)

We also use encapsulated JS to try. HTML and JS Code as follows. The background Code does not need to be modified, or directly fromRequest. Form. FilesGet it:

<div id="upfliediv"></div>

$ (Function (){



// Upload the instantiated object


$ ("# Upfliediv"). powerWebUpload ({

Auto: true, fileNumLimit: 1

});

$ ("# Upfliediv"). CleanUpload ();


})

Upload effect:

 

4. File Download.

The file has been uploaded. Of course we need to download it.

Directly downloading through URL + address is an extremely insecure method. Here we use the returned stream to download.

The background code is as follows:

/// <Summary>

/// File stream output // </summary>

/// <Returns> </returns>

Public IActionResult DownLoad (string file)

{

Var addrUrl = file;

Var stream = System. IO. File. OpenRead (addrUrl );

String fileExt = GetFileExt (file );

// Obtain the ContentType of the object

Var provider = new FileExtensionContentTypeProvider ();

Var memi = provider. Mappings [fileExt];

Return File (stream, memi, Path. GetFileName (addrUrl ));

}

It is worth noting that we used to use MimeMapping. GetMimeMapping (file) directly for ContentType.

However, this class is under System. Web, and core has abandoned the existing System. Web.

Therefore, in ASP. NET Core, we need to use the new classFileExtensionContentTypeProviderTo obtain the ContentType of the object.

Compile the HTML + JS Code as follows (PS: it is simple to write because it is a demo ):

<Div> <input type = "text" id = "filename"/> <button onclick = "downLoad ()"> downLoad </button> </div>
 function downLoad() {            var filename = $("#filename").val();            window.location.href = "@Url.Action("DownLoad")?file=" + filename;        }

Effect:

Address: https://www.cnblogs.com/GuZhenYin/p/8194726.html

. NET community news, deep good article, welcome to visit the public number article summary http://www.csharpkit.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.