当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Core文件上传与下载实例(多种上传方式)

ASP.NET Core文件上传与下载实例(多种上传方式)

2018年01月25日  | 移动技术网IT编程  | 我要评论

破茧天魔1,妹妹恋人快播,后藤理沙

前言

前段时间项目上线,实在太忙,最近终于开始可以研究研究asp.net core了.

打算写个系列,但是还没想好目录,今天先来一篇,后面在整理吧.

asp.net core 2.0 发展到现在,已经很成熟了.下个项目争取使用吧.

正文

1.使用模型绑定上传文件(官方例子)

官方机器翻译的地址:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads

这里吐槽一下 - -,这tm的机器翻译..还不如自己看e文的..

首先我们需要创建一个form表单如下:

<form method="post" enctype="multipart/form-data" asp-controller="uploadfile" asp-action="filesave">
  <div>
   <div>
    <p>form表单多个上传文件:</p>
    <input type="file" name="files" multiple />
    <input type="submit" value="上传" />
   </div>
  </div>
 </form>

其中,asp-controller和asp-action,(这个是taghelper的玩法,以后讲)是我们要访问的控制器和方法.

给我们的input标签加上 multiple 属性,来支持多文件上传.

创建一个控制器,我们编写上传方法如下:

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); //文件扩展名,不含“.”
     long filesize = formfile.length; //获得文件大小,以字节为单位
     string newfilename = system.guid.newguid().tostring() + "." + fileext; //随机生成新的文件名
     var filepath = webrootpath +"/upload/" + newfilename;
     using (var stream = new filestream(filepath, filemode.create))
     {
      
      await formfile.copytoasync(stream);
     }
    }
   }
   return ok(new { count = files.count, size });
  }

这里我们采用asp.net core的新接口iformfile, iformfile的具体定义如下:

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);
}

上面的代码使用了ihostingenvironment来获取项目的根目录地址.

构造函数注入的代码如下:

private readonly ihostingenvironment _hostingenvironment;
  public uploadfilecontroller(ihostingenvironment hostingenvironment)
  {
   _hostingenvironment = hostingenvironment;
  }

这样,我们就完成了控制器的编写,然后到运行前端,上传文件..效果如下:

通过iformfile的copytoasync方法,我们就可以把这个文件流复制下来并保存到本地即可.

2.使用ajax上传文件

上面我们是使用表单上传,但是项目过程中,大部分情况会使用ajax进行上传,所以我们就来讲讲如何使用ajax上传.

首先编写html代码如下:

<div>
 <form id="uploadform">
  ajax上传多文件: <input type="file" name="file" multiple />
  <input type="button" value="上传" onclick="doupload()" />
 </form>
</div>

编写js代码如下(这里我们使用formdata对象来上传):

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);
   }
  });
  }

后台代码不做任何修改.我们会发现.直接在list<iformfile> files中是无法获取到文件的.

通过调试,我们可以发现,文件是上传成功的,但是放在了request.form.files当中.

所以修改后台代码如下:

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); //文件扩展名,不含“.”
     long filesize = formfile.length; //获得文件大小,以字节为单位
     string newfilename = system.guid.newguid().tostring() + "." + fileext; //随机生成新的文件名
     var filepath = webrootpath +"/upload/" + newfilename;
     using (var stream = new filestream(filepath, filemode.create))
     {
      
      await formfile.copytoasync(stream);
     }
    }
   }
   return ok(new { count = files.count, size });
 }

改为直接从request.form.files中获取文件集合.~

3.使用webuploader上传文件

很久之前..呃..封装过一个webuploader的js

..我们也用封装好的js来试试.html和js代码如下,后台代码不需要修改,还是直接从request.form.files获取即可:

<div id="upfliediv"></div>
$(function () {

  //实例化文件上传
  $("#upfliediv").powerwebupload({
    auto: true, filenumlimit: 1
   });
  $("#upfliediv").cleanupload();
 })

上传效果如图:

4.文件下载.

上传了文件,我们当然需要下载.

直接通过url+地址下载是一种极其不安全的方式.这里我们采用返回流的形式来下载.

后台代码如下:

/// <summary>
  /// 文件流的方式输出  /// </summary>
  /// <returns></returns>
  public iactionresult download(string file)
  {
   var addrurl = file;
   var stream = system.io.file.openread(addrurl);
   string fileext = getfileext(file);
   //获取文件的contenttype
   var provider = new fileextensioncontenttypeprovider();
   var memi = provider.mappings[fileext];
   return file(stream, memi, path.getfilename(addrurl));
  }

这里值得注意的是,以前我们想获取contenttype直接使用mimemapping.getmimemapping(file);就好了.

但是这个类是在system.web下的,core已经抛弃了现有的system.web.

所以在asp.net core中我们需要通过新的类fileextensioncontenttypeprovider来获取文件的contenttype

编写html+js代码如下(ps:因为是demo,所以写的比较简陋):

<div>
 <input type="text" id="filename" /><button onclick="download()">下载</button>
</div>
function download() {
   var filename = $("#filename").val();
   window.location.href = "@url.action("download")?file=" + filename;
}

效果如图:

以上这篇asp.net core文件上传与下载实例(多种上传方式)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网