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

Source: Internet
Author: User

1. Uploading files using model bindings (official example)

Address of official machine translation: Https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads

Here's a slot--this TM machine translation. You might as well read the E-paper yourself.

First we need to create a form form as follows:

<form method= "POST" enctype= "Multipart/form-data" asp-controller= "UploadFile" asp-action= "FileSave" >        <div>            <div>                <p>form form multiple upload files:</p>                <input type= "file" name= "files" multiple/ >                <input type= "Submit" value= "Upload"/>            </div>        </div>    </form>

Among them,Asp-controller and asp-action, (this is the play of Taghelper, later speaking) is the controller and method we want to access.

Add the multiple attribute to our input tag to support multiple file uploads.

To create a controller, we 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, not including "." Long fileSize = formfile.length; Gets the file size, in bytes, of string newfilename = System.Guid.NewGuid (). ToString () + "." + Fileext;                    Randomly generate a new file name 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 for ASP. Iformfile is defined 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 code above uses Ihostingenvironment to get the root directory address of the project.

The code for the constructor injection is as follows:

Private ReadOnly ihostingenvironment _hostingenvironment;        Public Uploadfilecontroller (ihostingenvironment hostingenvironment)        {            _hostingenvironment = hostingenvironment;        }

  

In this way, we complete the controller writing, and then to run the front end, upload files. The effect is as follows:

With Iformfile's Copytoasync method, we can copy this file stream and save it locally.

2. Uploading files using Ajax

We use form uploads above, but most of the project is uploaded using Ajax, so let's talk about using Ajax uploads.

First write the HTML code as follows:

<div>    <form id= "Uploadform" >        ajax uploads multiple files: <input type= "file" name= "file" multiple/>        <input type= "button" value= "Upload" onclick= "doupload ()"/>    </form></div>

Write 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 backend code does not make any changes. We'll find out. The file is not available directly in list<iformfile> files.

Through debugging, we can find that the file is uploaded successfully, but put in the Request.Form.Files .

So 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, not including "." Long fileSize = formfile.length; Gets the file size, in bytes, of string newfilename = System.Guid.NewGuid (). ToString () + "." + Fileext;                    Randomly generate a new file name var FilePath = Webrootpath + "/upload/" + newfilename;                                                using (var stream = new FileStream (FilePath, FileMode.Create)) {                    Await Formfile.copytoasync (stream);         }                }            }   Return Ok (New {count = files. Count, size}); }

  

Instead, get the collection of files directly from the Request.Form.Files .

3. Uploading files using Webuploader

A long time ago. Uh.. Encapsulates a Webuploader JS. The following:

Baidu Webuploader Open source upload Control two times package, thin front-end code (two code to get rid of upload)

Baidu Webuploader two times package, streamline the front-end Code Image preview upload (two code to do upload)

We also use the encapsulated JS to try. html and JS code as follows, the background code does not need to be modified, or directly from the Request.Form.Files get:

<div id= "Upfliediv" ></div>$ (function () {        ///instantiation File Upload        $ ("#upfliediv"). Powerwebupload ({                auto : True, Filenumlimit:1            });        $ ("#upfliediv"). Cleanupload ();    })

  

Upload effect:

4. File download.

Upload the file, of course we need to download.

Downloading directly through the url+ address is an extremely unsafe way. Here we use the return stream as the 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);            Get the file contenttype            var provider = new Fileextensioncontenttypeprovider ();            var Memi = provider. Mappings[fileext];            Return File (Stream, Memi, Path.getfilename (Addrurl));        }  

  

It is worth noting that previously we wanted to get ContentType directly using mimemapping.getmimemapping (file);

But this class is under System.Web, and the core has abandoned the existing system.web.

So in ASP. NET core we need a new class Fileextensioncontenttypeprovider to get the contenttype of the file.

Write the HTML+JS code as follows (PS: Because it is a demo, so it is relatively simple to write):

<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:

Guzhengyin Source: http://www.cnblogs.com/GuZhenYin/If you feel that reading this article is helpful to you, please click "Recommend" button, your "recommendation" will be my biggest writing motivation! This article is copyrighted by the author and the blog Park, welcome reprint, but without the consent of the author must retain this statement, and on the article page

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

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.