vue+webapi文件上传与下载

vue+webapi文件上传

话不多说直接上本人测试代码

VUE前端





后端

[HttpPost]
        public ResultModel fileSave()
        {
            var files = HttpContext.Current.Request.Files;
            var form = HttpContext.Current.Request.Form;
            string chunk = form["chunk"];
            string guid = form["guid"];

            //文件保存目录路径 
            string SaveTempPath = "~/FileCollection/";
            string dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath);

            ResultModel message = new ResultModel();
            var chunked = form["chunked"];
            if (chunked != null && chunked == "true")
            {
                message.data = Convert.ToInt32(chunk) + 1;
                string filePath = Path.Combine(dirTempPath, "TemporaryFiles", guid);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                for (int i = 0; i < files.Count; i++)
                {
                    var file = files[i];
                    //如果有文件
                    if (file.ContentLength > 0)
                    {
                        string dirPath = Path.Combine(filePath, $"{file.FileName}_{chunk}");
                        file.SaveAs(dirPath);
                    }
                }
            }
            else
            {
                string date = DateTime.Now.ToString("yyyy-MM-dd");
                string filePath = Path.Combine(dirTempPath, date, guid);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                for (int i = 0; i < files.Count; i++)
                {
                    var file = files[i];
                    //如果有文件
                    if (file.ContentLength > 0)
                    {
                        string dirPath = Path.Combine(filePath, file.FileName);
                        if (!File.Exists(dirPath))
                        {
                            file.SaveAs(dirPath);
                            string FilePath = $"/FileCollection/{date}/{guid}/{file.FileName}";
                            string SQL = string.Format(@"insert into tab_File (UserName,FileName,FileSize,FilePath) values('{0}','{1}','{2}','{3}')"
                                                    , "小范", file.FileName, Convert.ToInt64(form["fullSize"]), FilePath);
                            int flag = new DBHelper().Execute(SQL);
                        }
                    }
                }
            }
            message.code = 0;
            message.msg = "上传成功";
            return message;
        }

        [HttpPost]
        public async Task fileMerge([FromBody] FileValidDto valid)
        {
            ResultModel message = new ResultModel { code = 0 };
            string fileName = valid.fileName;
            if (string.IsNullOrEmpty(fileName))
            {
                message.msg = "文件名不能为空";
                message.data = false;
                return message;
            }
            //最终上传完成后,请求合并返回合并消息
            try
            {
                //文件保存目录路径 
                string SaveTempPath = "~/FileCollection/";
                string dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath);
                string guid = valid.guid;
                int fileCount = valid.chunks;

                string filePath = Path.Combine(dirTempPath, "TemporaryFiles", guid);
                var files = Directory.GetFiles(filePath);
                if (fileCount != files.Count())
                {
                    Directory.Delete(filePath, true);
                    message.msg = "文件上传失败";
                    message.data = false;
                    return message;
                }
                string date = DateTime.Now.ToString("yyyy-MM-dd");
                string fileFinalPath = Path.Combine(dirTempPath, date, guid);
                if (!Directory.Exists(fileFinalPath))
                {
                    Directory.CreateDirectory(fileFinalPath);
                }
                string fileFinalName = Path.Combine(fileFinalPath, fileName);
                FileStream fs = new FileStream(fileFinalName, FileMode.Create);
                foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))
                {
                    var bytes = File.ReadAllBytes(part);
                    await fs.WriteAsync(bytes, 0, bytes.Length);
                    File.Delete(part);//删除分块
                }
                fs.Close();
              
                Directory.Delete(filePath);
               
                string FilePath = $"/FileCollection/{date}/{guid}/{fileName}";
                string SQL = string.Format(@"insert into tab_File (UserName,FileName,FileSize,FilePath) values('{0}','{1}','{2}','{3}')"
                                        , "小范", fileName, valid.fullSize, FilePath);
                int flag = new DBHelper().Execute(SQL);
                message.msg = "上传成功";
                message.data = true;
            }
            catch (Exception ex)
            {
                message.code = 1;
                message.msg = "合并文件失败,请重新上传";
            }
            return message;
        }

        [HttpPost]
        public ResultModel FileDownload()
        {
            var form = HttpContext.Current.Request.Form;
            var fid = form["fid"];
            try
            {
                DataSet ds = new DBHelper().GetDataSet("select * from tab_File where id=" + fid);
                var list = Command.DataSetToList(ds).FirstOrDefault();
                //文件保存目录路径 
                string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/"), list.FilePath);
                return new ResultModel
                {
                    code = 0,
                    msg = "下载",
                    data = filePath
                };
            }
            catch (Exception ex)
            {
                return new ResultModel
                {
                    code = 0,
                    msg = ex.Message
                };
            }
        }

vue+webapi文件下载

VUE前端

事件
 下载
方法
 handleDownLoad(index, row) {
      var param = new FormData();
      param.append("fid", index);
      param.append("fileName", row.FileName);
      let res = store.dispatch("upload/getFileFrom", row.Id);
      const blob = new Blob([res.data]); //new Blob([res])中不加data就会返回下图中[objece objece]内容(少取一层)
      const fileName = row.FileName; //下载文件名称
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
    },
路由
import { getFileFrom } from '@/api/upload'

const actions = {
  // getFileFrom
  getFileFrom({ commit }, fid) {
    return new Promise((resolve, reject) => {
      getFileFrom(fid).then(response => {
        resolve(response)
        //resolve(response.data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  actions
}

export function getFileFrom(fid) {
  return request({
    url: '/book/getFileFrom?fid=' + fid,
    method: 'get',
  })
}

webapi后端

		//响应的MimeType类型
        private const string MimeType = "application/octet-stream";
        /// 
        /// 缓冲区大小
        /// 
        private const int BufferSize = 80 * 1024;
        [HttpGet]
        public ResultModel GetFileFrom(int fid)
        {
            try
            {
                DataSet ds = new DBHelper().GetDataSet("select * from tab_File where id=" + fid);
                var list = Command.DataSetToList(ds).FirstOrDefault();
                var FilePath = System.Web.Hosting.HostingEnvironment.MapPath("~"+list.FilePath); //获取文件路径
                var fullFilePath = FilePath;
                if (!File.Exists(fullFilePath))
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                FileStream fileStream = File.Open(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var response = new HttpResponseMessage();
                response.Content = new StreamContent(fileStream, BufferSize);
                response.Content.Headers.ContentDisposition
                    = new ContentDispositionHeaderValue("attachment") { FileName = list.FileName };//list.FileName 文件名称
                response.Content.Headers.ContentType
                    = new MediaTypeHeaderValue(MimeType);
                response.Content.Headers.ContentLength
                    = fileStream.Length;
                //return response;
                return new ResultModel
                {
                    code = 0,
                    msg = "下载",
                    data = response
                };
            }
            catch(Exception ex)
            {
                return new ResultModel
                {
                    code = 0,
                    msg = ex.Message
                };
            }
        }

你可能感兴趣的:(vue.js,前端,javascript)