旗下导航:搜·么
当前位置:网站首页 > .Net教程 > 正文

asp.net core分块上传文件示例【C#.Net教程】,asp.net core 上传

作者:搜教程发布时间:2019-11-27分类:.Net教程浏览:69评论:0


导读:写完asp.net多文件上传后,以为这类上传照样有许多缺点,因而。。。(省略一万字,不空话)。这里我没用传统的asp.net,而挑选了开源的asp.netcore,缘由很简单,....
写完asp.net多文件上传后,以为这类上传照样有许多缺点,因而。。。(省略一万字,不空话)。这里我没用传统的asp.net,而挑选了开源的asp.net core,缘由很简单,.net core是.net新的最先,更是.net和.net开发者的将来,愿望.net生长越来越好(人人的工资越来越高(●ˇ∀ˇ●))。

1.前端的完成:

1).html: 

<html>
<head>
  <meta name="viewport" content="width=device-width" />
  <title>Index</title>
  <link href="/lib/bootstrap/dist/css/bootstrap.css" rel="external nofollow" rel="stylesheet" />
  <script src="/lib/jquery/dist/jquery.js"></script>
  <script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
  <script src="/js/UploadJs.js"></script>
</head>
<body>
  <p class="row" style="margin-top:20%">
    <p class="col-lg-4"></p>
    <p class="col-lg-4">
      <input type="text" value="请挑选文件" size="20" name="upfile" id="upfile" style="border:1px dotted #ccc">
      <input type="button" value="阅读" onclick="path.click()" style="border:1px solid #ccc;background:#fff">
      <input type="file" id="path" style="display:none" multiple="multiple" onchange="upfile.value=this.value">
      <br />
      <span id="output">0%</span>
      <button type="button" id="file" onclick="UploadStart()" style="border:1px solid #ccc;background:#fff">最先上传</button>
    </p>
    <p class="col-lg-4"></p>
  </p>
</body>
</html>

2).javascript:

var UploadPath = "";
//最先上传
function UploadStart() {
  var file = $("#path")[0].files[0];
  AjaxFile(file, 0);
}
function AjaxFile(file, i) {
  var name = file.name, //文件名
  size = file.size, //总大小shardSize = 2 * 1024 * 1024, 
  shardSize = 2 * 1024 * 1024,//以2MB为一个分片
  shardCount = Math.ceil(size / shardSize); //总片数
  if (i >= shardCount) {
    return;
  }
  //盘算每一片的肇端与完毕位置
  var start = i * shardSize,
  end = Math.min(size, start + shardSize);
  //组织一个表单,FormData是HTML5新增的
  var form = new FormData();
  form.append("data", file.slice(start, end)); //slice要领用于切出文件的一部分
  form.append("lastModified", file.lastModified);
  form.append("fileName", name);
  form.append("total", shardCount); //总片数
  form.append("index", i + 1); //当前是第几片
  UploadPath = file.lastModified
  //Ajax提交文件
  $.ajax({
    url: "/Upload/UploadFile",
    type: "POST",
    data: form,
    async: true, //异步
    processData: false, //很重要,通知jquery不要对form举行处置惩罚
    contentType: false, //很重要,指定为false才构成准确的Content-Type
    success: function (result) {
      if (result != null) {
        i = result.number++;
        var num = Math.ceil(i * 100 / shardCount);
        $("#output").text(num + '%');
        AjaxFile(file, i);
        if (result.mergeOk) {
          var filepath = $("#path");
          filepath.after(filepath.clone().val(""));
          filepath.remove();//清空input file
          $('#upfile').val('请挑选文件');
          alert("success!!!");
        }
      }
    }
  });
}

这里的重要思绪是应用html5 File api的slice要领把文件分块,然后new一个FormData()对象用于贮存文件数据,以后就是递归挪用AjaxFile要领直至上传完毕。

2.背景C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.IO;

// For more information on enabling MVC for empty projects, visit http://www.ki4.cn/

namespace DotNet.Upload.Controllers
{
  public class UploadController : Controller
  {
    // GET: /<controller>/
    public IActionResult Index()
    {
      return View();
    }

    [HttpPost]
    public async Task<ActionResult> UploadFile()
    {
      var data = Request.Form.Files["data"];
      string lastModified = Request.Form["lastModified"].ToString();
      var total = Request.Form["total"];
      var fileName = Request.Form["fileName"];
      var index = Request.Form["index"];

      string temporary = Path.Combine(@"E:\阅读器", lastModified);//暂时保留分块的目次
      try
      {
        if (!Directory.Exists(temporary))
          Directory.CreateDirectory(temporary);
        string filePath = Path.Combine(temporary, index.ToString());
        if (!Convert.IsDBNull(data))
        {
          await Task.Run(() => {
            FileStream fs = new FileStream(filePath, FileMode.Create);
            data.CopyTo(fs);
          });
        }
        bool mergeOk = false;
        if (total == index)
        {
          mergeOk = await FileMerge(lastModified, fileName);
        }

        Dictionary<string, object> result = new Dictionary<string, object>();
        result.Add("number", index);
        result.Add("mergeOk", mergeOk);
        return Json(result);

      }
      catch (Exception ex)
      {
        Directory.Delete(temporary);//删除文件夹
        throw ex;
      }
    }

    public async Task<bool> FileMerge(string lastModified,string fileName)
    {
      bool ok = false;
      try
      {
        var temporary = Path.Combine(@"E:\阅读器", lastModified);//暂时文件夹
        fileName = Request.Form["fileName"];//文件名
        string fileExt = Path.GetExtension(fileName);//猎取文件后缀
        var files = Directory.GetFiles(temporary);//取得下面的一切文件
        var finalPath = Path.Combine(@"E:\阅读器", DateTime.Now.ToString("yyMMddHHmmss") + fileExt);//终究的文件名(demo中保留的是它上传时刻的文件名,实际操作一定不能如许)
        var fs = new FileStream(finalPath, FileMode.Create);
        foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保证从0-N Write
        {
          var bytes = System.IO.File.ReadAllBytes(part);
          await fs.WriteAsync(bytes, 0, bytes.Length);
          bytes = null;
          System.IO.File.Delete(part);//删除分块
        }
        fs.Close();
        Directory.Delete(temporary);//删除文件夹
        ok = true;
      }
      catch (Exception ex)
      {
        throw ex;
      }
      return ok;
    }

  }
}

这里的思绪就是先保留每个分块的文件到一个暂时文件夹,末了再经由过程FileStream兼并这些暂时文件(兼并时必须要按递次)。背景的要领都举行了异步化(async await真的异常好用),虽然不知道对效力有无提拔,然则就是以为如许很酷。

源码下载:DotNet_jb51.rar

以上就是本文的全部内容,愿望对人人的进修有所协助,也愿望人人多多支撑ki4网。

更多asp.net core分块上传文件示例相干文章请关注ki4网!

标签:asp.net core 上传


欢迎 发表评论: