ASP. NET Core Learning Notes (upload/download files file upload and download)

Source: Internet
Author: User
Tags ziparchive

2017-09-25

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

Https://www.codeproject.com/Articles/1203408/Upload-Download-Files-in-ASP-NET-Core

This is just about small file uploads.

First look at the front-end JS code

<inputID= "Inputfile"type= "File" /><Script>document.getElementById ('Inputfile'). AddEventListener (' Change', (e)={Let files=E.target.files; Let FormData= NewFormData (); Formdata.append ("file", files[0]); Let HTTP= NewXMLHttpRequest (); Http.open ('POST', '/upload-file', true);     Http.send (FormData); }, false); </Script>

If you want to upload multiple files, just append a few more.

C#

 Public classuploadfiledata{ PublicIformfile file {Get;Set; }} [Area ("Web")] Public classuploadcontroller:controller{ PublicUploadcontroller (ihostingenvironment environment) { This. Environment =environment; }    PrivateIhostingenvironment Environment {Get;Set; } [HttpPost ("Upload-file")]     Public AsyncTask<iactionresult>uploadfile (uploadfiledata data) {varAllfiles = Request.Form.Files;//multiple files can be obtained directly from the form.        varRoot =environment.        Webrootpath; varExtension =path.getextension (data.file.FileName); varGUID =Guid.NewGuid ().        ToString (); varFullPath = $@"{root}\images\{guid + extension}"; using(FileStream stream =NewFileStream (FullPath, FileMode.Create)) {            awaitData.file.CopyToAsync (stream); }         returnOk (); } [Route ("Upload")]     Public AsyncTask<iactionresult>Index () {returnView (); }}

Above is the simplest version, create file and then write the upload file stream

There is also a common scenario is that uploading images to do EXIF processing.

The core can now be supported with magick.net, but it seems to support only the window scene. If you are not windows you may want to wait or use a different plugin.

using(varstream =Data.file.OpenReadStream ())using(Magickimage image =NewMagickimage (Stream)) {Exifprofile profile=image.    Getexifprofile (); Image. Settings.setdefine (Magickformat.jpeg,"Sampling-factor","4:2:0"); Image. Strip (); //This will wash out all the EXIF images.Image. Quality = -; if(Profile! =NULL) {Exifvalue orientation= Profile. Values.singleordefault (v = V.tag = =exiftag.orientation); if(Orientation! =NULL)        {            intOrientationint =Convert.ToInt32 (orientation.            Value); if(Orientationint = =6) {image. Rotate ( -); }            Else if(Orientationint = =8) {image. Rotate (- -); }            Else if(Orientationint = =8) {image. Rotate ( the); }} image.    Write (FullPath); }    Else{image.    Write (FullPath); }}

It's simple.

One more zip.

using(varstream =Data.file.OpenReadStream ())using(varCompressedfilestream =NewFileStream ($@"{root}\images\{guid}.zip", FileMode.Create))using(varZiparchive =NewZiparchive (Compressedfilestream, Ziparchivemode.update,false)){    varZipEntry =ziparchive.createentry (data.file.FileName); using(varZipentrystream =Zipentry.open ()) {stream.    CopyTo (Zipentrystream); }}

Core Support Ziparchive OH

Download is also easy

 PublicUploadcontroller (ihostingenvironment environment, Icontenttypeprovider Contenttypeprovider) { This. Environment =environment;  This. Contenttypeprovider =Contenttypeprovider;}PrivateIhostingenvironment Environment {Get;Set; }PrivateIcontenttypeprovider Contenttypeprovider {Get;Set; } [HttpGet ("Download-file")] PublicFileresult DownloadFile (stringNamestringdisplay) {    stringContentType; Contenttypeprovider.trygetcontenttype (Name, outContentType); HttpContext.Response.ContentType=ContentType; stringPath = environment. Webrootpath +@"\images\"+ Name;//Note Oh, do not use the client's value directly as me to stitch the path, dangerousFilecontentresult result =NewFilecontentresult (System.IO.File.ReadAllBytes (path), ContentType) {filedownloadname=display}; returnresult;}

Html

<href= "/download-file?name=123.jpg&display=aaa.jpg"  download   >download</a>

ASP. NET Core Learning Notes (upload/download files file upload and download)

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.