.NET MVC实现文件上传和下载

1. 文件上传实现方法

private readonly string _savePath = "D:\\Document"; //指定保存的根目录
[HttpPost]
public async Task<JsonResult> Upload()
{
    try
    {
        var files = Request.Form.Files; // 这里获取上传的文件
        if (files == null)
        {
            throw new Exception("Uploaded file is empty");
        }

        // 创建保存目录
        var saveFolder = Path.Combine(_savePath, "TestUpload");
        if (!Directory.Exists(saveFolder))
        {
            Directory.CreateDirectory(saveFolder); // 不存在创建目录
        }

        foreach (var file in files)
        {
            var extension = new FileInfo(file.FileName).Extension; // 获取上传文件扩展名
            var fileName = $"{DateTime.Now.ToFileTime()}{extension}"; // 重命名,按时间保存, 避免文件名重复

            var saveFilePath = Path.Combine(saveFolder, fileName); // 保存位置
            //if (System.IO.File.Exists(saveFilePath))
            //{
            //    System.IO.File.Delete(saveFilePath); // 判断文件是否已存在,这里每次都会重命名,故一定不会重复
            //}
            using (var stream = new FileStream(saveFilePath, FileMode.CreateNew))
            {
                await file.CopyToAsync(stream);
            }
        }

        return new JsonResult(new { Code = 200, Message = "OK" });
    }
    catch (Exception ex)
    {
        // 返回异常的信息
        return new JsonResult(new { Code = 500, Message = ex.Message });
    }
}

2. 文件下载实现方法

private readonly string _savePath = "D:\\Document"; //指定保存的根目录
[HttpGet]
public FileResult Download(string fileName)
{
        var filePath= Path.Combine(_savePath , fileName);
        if (System.IO.File.Exists(filePath))
        {
            var res = this.PhysicalFile(filePath, MimeMapping.GetMimeMapping(fileName));
            // var res = this.File(new FileStream(filePath, FileMode.Open)); // 这两种方法都可以实现
            return res;
        }
       throw new Exception("File does not exist.");
}

3. MimeMapping

public static class MimeMapping
    {
        private static Hashtable _mimeMappingTable;

        private static void AddMimeMapping(string extension, string MimeType)
        {
            MimeMapping._mimeMappingTable.Add(extension, MimeType);
        }

        public static string GetMimeMapping(string FileName)
        {
            string text = null;
            int num = FileName.LastIndexOf('.');
            if (0 < num && num > FileName.LastIndexOf('\\'))
            {
                text = (string)MimeMapping._mimeMappingTable[FileName.Substring(num)];
            }
            if (text == null)
            {
                text = (string)MimeMapping._mimeMappingTable[".*"];
            }
            return text;
        }

        static MimeMapping()
        {
            MimeMapping._mimeMappingTable = new Hashtable(190, StringComparer.CurrentCultureIgnoreCase);
            MimeMapping.AddMimeMapping(".323", "text/h323");
            MimeMapping.AddMimeMapping(".asx", "video/x-ms-asf");
            MimeMapping.AddMimeMapping(".acx", "application/internet-property-stream");
            MimeMapping.AddMimeMapping(".ai", "application/postscript");
            MimeMapping.AddMimeMapping(".aif", "audio/x-aiff");
            MimeMapping.AddMimeMapping(".aiff", "audio/aiff");
            MimeMapping.AddMimeMapping(".axs", "application/olescript");
            MimeMapping.AddMimeMapping(".aifc", "audio/aiff");
            MimeMapping.AddMimeMapping(".asr", "video/x-ms-asf");
            MimeMapping.AddMimeMapping(".avi", "video/x-msvideo");
            MimeMapping.AddMimeMapping(".asf", "video/x-ms-asf");
            MimeMapping.AddMimeMapping(".au", "audio/basic");
            MimeMapping.AddMimeMapping(".application", "application/x-ms-application");
            MimeMapping.AddMimeMapping(".bin", "application/octet-stream");
            MimeMapping.AddMimeMapping(".bas", "text/plain");
            MimeMapping.AddMimeMapping(".bcpio", "application/x-bcpio");
            MimeMapping.AddMimeMapping(".bmp", "image/bmp");
            MimeMapping.AddMimeMapping(".cdf", "application/x-cdf");
            MimeMapping.AddMimeMapping(".cat", "application/vndms-pkiseccat");
            MimeMapping.AddMimeMapping(".crt", "application/x-x509-ca-cert");
            MimeMapping.AddMimeMapping(".c", "text/plain");
            MimeMapping.AddMimeMapping(".css", "text/css");
            MimeMapping.AddMimeMapping(".cer", "application/x-x509-ca-cert");
            MimeMapping.AddMimeMapping(".crl", "application/pkix-crl");
            MimeMapping.AddMimeMapping(".cmx", "image/x-cmx");
            MimeMapping.AddMimeMapping(".csh", "application/x-csh");
            MimeMapping.AddMimeMapping(".cod", "image/cis-cod");
            MimeMapping.AddMimeMapping(".cpio", "application/x-cpio");
            MimeMapping.AddMimeMapping(".clp", "application/x-msclip");
            MimeMapping.AddMimeMapping(".crd", "application/x-mscardfile");
            MimeMapping.AddMimeMapping(".deploy", "application/octet-stream");
            MimeMapping.AddMimeMapping(".dll", "application/x-msdownload");
            MimeMapping.AddMimeMapping(".dot", "application/msword");
            MimeMapping.AddMimeMapping(".doc", "application/msword");
            MimeMapping.AddMimeMapping(".dvi", "application/x-dvi");
            MimeMapping.AddMimeMapping(".dir", "application/x-director");
            MimeMapping.AddMimeMapping(".dxr", "application/x-director");
            MimeMapping.AddMimeMapping(".der", "application/x-x509-ca-cert");
            MimeMapping.AddMimeMapping(".dib", "image/bmp");
            MimeMapping.AddMimeMapping(".dcr", "application/x-director");
            MimeMapping.AddMimeMapping(".disco", "text/xml");
            MimeMapping.AddMimeMapping(".exe", "application/octet-stream");
            MimeMapping.AddMimeMapping(".etx", "text/x-setext");
            MimeMapping.AddMimeMapping(".evy", "application/envoy");
            MimeMapping.AddMimeMapping(".eml", "message/rfc822");
            MimeMapping.AddMimeMapping(".eps", "application/postscript");
            MimeMapping.AddMimeMapping(".flr", "x-world/x-vrml");
            MimeMapping.AddMimeMapping(".fif", "application/fractals");
            MimeMapping.AddMimeMapping(".gtar", "application/x-gtar");
            MimeMapping.AddMimeMapping(".gif", "image/gif");
            MimeMapping.AddMimeMapping(".gz", "application/x-gzip");
            MimeMapping.AddMimeMapping(".hta", "application/hta");
            MimeMapping.AddMimeMapping(".htc", "text/x-component");
            MimeMapping.AddMimeMapping(".htt", "text/webviewhtml");
            MimeMapping.AddMimeMapping(".h", "text/plain");
            MimeMapping.AddMimeMapping(".hdf", "application/x-hdf");
            MimeMapping.AddMimeMapping(".hlp", "application/winhlp");
            MimeMapping.AddMimeMapping(".html", "text/html");
            MimeMapping.AddMimeMapping(".htm", "text/html");
            MimeMapping.AddMimeMapping(".hqx", "application/mac-binhex40");
            MimeMapping.AddMimeMapping(".isp", "application/x-internet-signup");
            MimeMapping.AddMimeMapping(".iii", "application/x-iphone");
            MimeMapping.AddMimeMapping(".ief", "image/ief");
            MimeMapping.AddMimeMapping(".ivf", "video/x-ivf");
            MimeMapping.AddMimeMapping(".ins", "application/x-internet-signup");
            MimeMapping.AddMimeMapping(".ico", "image/x-icon");
            MimeMapping.AddMimeMapping(".jpg", "image/jpeg");
            MimeMapping.AddMimeMapping(".jfif", "image/pjpeg");
            MimeMapping.AddMimeMapping(".jpe", "image/jpeg");
            MimeMapping.AddMimeMapping(".jpeg", "image/jpeg");
            MimeMapping.AddMimeMapping(".js", "application/x-javascript");
            MimeMapping.AddMimeMapping(".lsx", "video/x-la-asf");
            MimeMapping.AddMimeMapping(".latex", "application/x-latex");
            MimeMapping.AddMimeMapping(".lsf", "video/x-la-asf");
            MimeMapping.AddMimeMapping(".manifest", "application/x-ms-manifest");
            MimeMapping.AddMimeMapping(".mhtml", "message/rfc822");
            MimeMapping.AddMimeMapping(".mny", "application/x-msmoney");
            MimeMapping.AddMimeMapping(".mht", "message/rfc822");
            MimeMapping.AddMimeMapping(".mid", "audio/mid");
            MimeMapping.AddMimeMapping(".mpv2", "video/mpeg");
            MimeMapping.AddMimeMapping(".man", "application/x-troff-man");
            MimeMapping.AddMimeMapping(".mvb", "application/x-msmediaview");
            MimeMapping.AddMimeMapping(".mpeg", "video/mpeg");
            MimeMapping.AddMimeMapping(".m3u", "audio/x-mpegurl");
            MimeMapping.AddMimeMapping(".mdb", "application/x-msaccess");
            MimeMapping.AddMimeMapping(".mpp", "application/vnd.ms-project");
            MimeMapping.AddMimeMapping(".m1v", "video/mpeg");
            MimeMapping.AddMimeMapping(".mpa", "video/mpeg");
            MimeMapping.AddMimeMapping(".me", "application/x-troff-me");
            MimeMapping.AddMimeMapping(".m13", "application/x-msmediaview");
            MimeMapping.AddMimeMapping(".movie", "video/x-sgi-movie");
            MimeMapping.AddMimeMapping(".m14", "application/x-msmediaview");
            MimeMapping.AddMimeMapping(".mpe", "video/mpeg");
            MimeMapping.AddMimeMapping(".mp2", "video/mpeg");
            MimeMapping.AddMimeMapping(".mov", "video/quicktime");
            MimeMapping.AddMimeMapping(".mp3", "audio/mpeg");
            MimeMapping.AddMimeMapping(".mpg", "video/mpeg");
            MimeMapping.AddMimeMapping(".ms", "application/x-troff-ms");
            MimeMapping.AddMimeMapping(".nc", "application/x-netcdf");
            MimeMapping.AddMimeMapping(".nws", "message/rfc822");
            MimeMapping.AddMimeMapping(".oda", "application/oda");
            MimeMapping.AddMimeMapping(".ods", "application/oleobject");
            MimeMapping.AddMimeMapping(".pmc", "application/x-perfmon");
            MimeMapping.AddMimeMapping(".p7r", "application/x-pkcs7-certreqresp");
            MimeMapping.AddMimeMapping(".p7b", "application/x-pkcs7-certificates");
            MimeMapping.AddMimeMapping(".p7s", "application/pkcs7-signature");
            MimeMapping.AddMimeMapping(".pmw", "application/x-perfmon");
            MimeMapping.AddMimeMapping(".ps", "application/postscript");
            MimeMapping.AddMimeMapping(".p7c", "application/pkcs7-mime");
            MimeMapping.AddMimeMapping(".pbm", "image/x-portable-bitmap");
            MimeMapping.AddMimeMapping(".ppm", "image/x-portable-pixmap");
            MimeMapping.AddMimeMapping(".pub", "application/x-mspublisher");
            MimeMapping.AddMimeMapping(".pnm", "image/x-portable-anymap");
            MimeMapping.AddMimeMapping(".png", "image/png");
            MimeMapping.AddMimeMapping(".pml", "application/x-perfmon");
            MimeMapping.AddMimeMapping(".p10", "application/pkcs10");
            MimeMapping.AddMimeMapping(".pfx", "application/x-pkcs12");
            MimeMapping.AddMimeMapping(".p12", "application/x-pkcs12");
            MimeMapping.AddMimeMapping(".pdf", "application/pdf");
            MimeMapping.AddMimeMapping(".pps", "application/vnd.ms-powerpoint");
            MimeMapping.AddMimeMapping(".p7m", "application/pkcs7-mime");
            MimeMapping.AddMimeMapping(".pko", "application/vndms-pkipko");
            MimeMapping.AddMimeMapping(".ppt", "application/vnd.ms-powerpoint");
            MimeMapping.AddMimeMapping(".pmr", "application/x-perfmon");
            MimeMapping.AddMimeMapping(".pma", "application/x-perfmon");
            MimeMapping.AddMimeMapping(".pot", "application/vnd.ms-powerpoint");
            MimeMapping.AddMimeMapping(".prf", "application/pics-rules");
            MimeMapping.AddMimeMapping(".pgm", "image/x-portable-graymap");
            MimeMapping.AddMimeMapping(".qt", "video/quicktime");
            MimeMapping.AddMimeMapping(".ra", "audio/x-pn-realaudio");
            MimeMapping.AddMimeMapping(".rgb", "image/x-rgb");
            MimeMapping.AddMimeMapping(".ram", "audio/x-pn-realaudio");
            MimeMapping.AddMimeMapping(".rmi", "audio/mid");
            MimeMapping.AddMimeMapping(".ras", "image/x-cmu-raster");
            MimeMapping.AddMimeMapping(".roff", "application/x-troff");
            MimeMapping.AddMimeMapping(".rtf", "application/rtf");
            MimeMapping.AddMimeMapping(".rtx", "text/richtext");
            MimeMapping.AddMimeMapping(".sv4crc", "application/x-sv4crc");
            MimeMapping.AddMimeMapping(".spc", "application/x-pkcs7-certificates");
            MimeMapping.AddMimeMapping(".setreg", "application/set-registration-initiation");
            MimeMapping.AddMimeMapping(".snd", "audio/basic");
            MimeMapping.AddMimeMapping(".stl", "application/vndms-pkistl");
            MimeMapping.AddMimeMapping(".setpay", "application/set-payment-initiation");
            MimeMapping.AddMimeMapping(".stm", "text/html");
            MimeMapping.AddMimeMapping(".shar", "application/x-shar");
            MimeMapping.AddMimeMapping(".sh", "application/x-sh");
            MimeMapping.AddMimeMapping(".sit", "application/x-stuffit");
            MimeMapping.AddMimeMapping(".spl", "application/futuresplash");
            MimeMapping.AddMimeMapping(".sct", "text/scriptlet");
            MimeMapping.AddMimeMapping(".scd", "application/x-msschedule");
            MimeMapping.AddMimeMapping(".sst", "application/vndms-pkicertstore");
            MimeMapping.AddMimeMapping(".src", "application/x-wais-source");
            MimeMapping.AddMimeMapping(".sv4cpio", "application/x-sv4cpio");
            MimeMapping.AddMimeMapping(".tex", "application/x-tex");
            MimeMapping.AddMimeMapping(".tgz", "application/x-compressed");
            MimeMapping.AddMimeMapping(".t", "application/x-troff");
            MimeMapping.AddMimeMapping(".tar", "application/x-tar");
            MimeMapping.AddMimeMapping(".tr", "application/x-troff");
            MimeMapping.AddMimeMapping(".tif", "image/tiff");
            MimeMapping.AddMimeMapping(".txt", "text/plain");
            MimeMapping.AddMimeMapping(".texinfo", "application/x-texinfo");
            MimeMapping.AddMimeMapping(".trm", "application/x-msterminal");
            MimeMapping.AddMimeMapping(".tiff", "image/tiff");
            MimeMapping.AddMimeMapping(".tcl", "application/x-tcl");
            MimeMapping.AddMimeMapping(".texi", "application/x-texinfo");
            MimeMapping.AddMimeMapping(".tsv", "text/tab-separated-values");
            MimeMapping.AddMimeMapping(".ustar", "application/x-ustar");
            MimeMapping.AddMimeMapping(".uls", "text/iuls");
            MimeMapping.AddMimeMapping(".vcf", "text/x-vcard");
            MimeMapping.AddMimeMapping(".wps", "application/vnd.ms-works");
            MimeMapping.AddMimeMapping(".wav", "audio/wav");
            MimeMapping.AddMimeMapping(".wrz", "x-world/x-vrml");
            MimeMapping.AddMimeMapping(".wri", "application/x-mswrite");
            MimeMapping.AddMimeMapping(".wks", "application/vnd.ms-works");
            MimeMapping.AddMimeMapping(".wmf", "application/x-msmetafile");
            MimeMapping.AddMimeMapping(".wcm", "application/vnd.ms-works");
            MimeMapping.AddMimeMapping(".wrl", "x-world/x-vrml");
            MimeMapping.AddMimeMapping(".wdb", "application/vnd.ms-works");
            MimeMapping.AddMimeMapping(".wsdl", "text/xml");
            MimeMapping.AddMimeMapping(".xap", "application/x-silverlight-app");
            MimeMapping.AddMimeMapping(".xml", "text/xml");
            MimeMapping.AddMimeMapping(".xlm", "application/vnd.ms-excel");
            MimeMapping.AddMimeMapping(".xaf", "x-world/x-vrml");
            MimeMapping.AddMimeMapping(".xla", "application/vnd.ms-excel");
            MimeMapping.AddMimeMapping(".xls", "application/vnd.ms-excel");
            MimeMapping.AddMimeMapping(".xof", "x-world/x-vrml");
            MimeMapping.AddMimeMapping(".xlt", "application/vnd.ms-excel");
            MimeMapping.AddMimeMapping(".xlc", "application/vnd.ms-excel");
            MimeMapping.AddMimeMapping(".xsl", "text/xml");
            MimeMapping.AddMimeMapping(".xbm", "image/x-xbitmap");
            MimeMapping.AddMimeMapping(".xlw", "application/vnd.ms-excel");
            MimeMapping.AddMimeMapping(".xpm", "image/x-xpixmap");
            MimeMapping.AddMimeMapping(".xwd", "image/x-xwindowdump");
            MimeMapping.AddMimeMapping(".xsd", "text/xml");
            MimeMapping.AddMimeMapping(".z", "application/x-compress");
            MimeMapping.AddMimeMapping(".zip", "application/x-zip-compressed");
            MimeMapping.AddMimeMapping(".*", "application/octet-stream");
        }
    }

4. 相关命名空间

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,772评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,458评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,610评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,640评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,657评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,590评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,962评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,631评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,870评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,611评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,704评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,386评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,969评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,944评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,179评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,742评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,440评论 2 342

推荐阅读更多精彩内容