Vue与.net Core API 文件下载
前端代码
/** * @param {Object} data * @param {Object} fileName * @description 转换格式后下载 */ download(data, fileName) { if (!data) return; console.log(data); const url = window.URL.createObjectURL(new Blob([data])); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', fileName); document.body.appendChild(link); link.click(); }, /** * @description 下载文件 */ async downFile(row) { const res = await this.$ajax({ method: 'get', url: `/5002/File/down/${row.id}`, responseType: 'blob' }) this.download(res, row.name) },
后端代码
private FileService _fileService; /// <summary> /// 文件服务 /// </summary> /// <param name="fileService"></param> public FileController(FileService fileService) { _fileService = fileService; } private readonly List<string> Images = new List<string>() { "jpg", "png", "bmp", "jpge" }; private readonly List<string> Files = new List<string>() { "txt", "doc", "docx", "xls", "pdf", "xlsx" }; /// <summary> /// 上传图片(JPG,PNG,BMP等图片文件) /// </summary> /// <returns></returns> [HttpPost("upload-img")] public async Task<BaseResponse<List<SysFile>>> UploadImg() { var files = Request.Form.Files; if (files.Count == 0) { throw new Exception("没有上传文件"); } foreach(var file in files) { var fileName = Path.GetFileName(file.FileName); //取得文件的扩展名 var fileExtension = Path.GetExtension(fileName).ToLower(); if (string.IsNullOrEmpty(fileExtension)) { throw new Exception("对不起,只能上传图片文件"); } fileExtension = fileExtension.Replace(".", ""); if (!Images.Contains(fileExtension)) { throw new Exception($"对不起,只能上传图片格式文件,文件类型为 [ {string.Join(",", Images)} ] 中的一种"); } } var result = await this.Upload("img", files); return BaseResponse.GetResult(result); } /// <summary> /// 上传文件(PDF,WORD,EXCEL,TXT等非图片类文件) /// </summary> /// <returns></returns> [HttpPost("upload-file")] public async Task< BaseResponse<List<SysFile>>> UploadFile() { var files = Request.Form.Files; if (files.Count == 0) { throw new Exception("没有上传文件"); } foreach (var file in files) { var fileName = Path.GetFileName(file.FileName); //取得文件的扩展名 var fileExtension = Path.GetExtension(fileName).ToLower(); if (string.IsNullOrEmpty(fileExtension)) { throw new Exception("对不起,只能上传文档类文件"); } fileExtension = fileExtension.Replace(".", ""); if (!Files.Contains(fileExtension)) { throw new Exception($"对不起,只能上传文档格式文件,文件类型为 [ {string.Join(",", Files)} ] 中的一种"); } } var result = await this.Upload("file", files); return BaseResponse.GetResult(result); } /// <summary> /// 上传 并将记录保存到数据库中 /// </summary> /// <param name="type"></param> /// <param name="files"></param> /// <returns></returns> private async Task<List<SysFile>> Upload(string type,IFormFileCollection files) { List<SysFile> result = new List<SysFile>(); string dir = DateTime.Now.ToString("yyyyMMdd"); string savePath = Path.Combine(AppContext.BaseDirectory, "wwwroot", "upload", type, dir); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } foreach (var file in files) { if (file.Length > 0) { string fileName, fileExtension; //取得上传得文件名 fileName = Path.GetFileName(file.FileName); //取得文件的扩展名 fileExtension = Path.GetExtension(fileName).ToLower(); string newFileName = $"{ Guid.NewGuid().ToString()}{ fileExtension}"; using (var stream = new FileStream(Path.Combine(savePath, newFileName), FileMode.Create)) { file.CopyToAsync(stream).Wait(); var filePath = $"/upload/{type}/{dir}/{newFileName}"; result.Add(new SysFile() { FileEx = fileExtension, FileName = fileName, Path = filePath, UploadUser = User.Identity.Name }); } } } result = await _fileService.CreateAsync(result); return result; } /// <summary> /// 获取文件详情 /// </summary> /// <param name="id">SysFile.ID</param> /// <returns></returns> [HttpGet("file-info/{id}")] public BaseResponse<SysFile> GetFileInfo(string id) { var file = _fileService.Get(id); return BaseResponse.GetResult(file); } /// <summary> /// 文件下载 /// </summary> /// <param name="id">SysFile.ID</param> /// <returns>application/octet-stream</returns> [HttpGet("down/{id}")] public IActionResult Down(string id) { var file = _fileService.Get(id); var paths = file.Path.Split("/").ToList(); paths.Remove(paths.First()); paths.Insert(0, AppContext.BaseDirectory); paths.Insert(1, "wwwroot"); var filePath = Path.Combine(paths.ToArray()); if (System.IO.File.Exists(filePath)) { return PhysicalFile(filePath, "application/octet-stream", file.FileName); } else { throw new Exception($"下载失败!未能找到指定文件,文件ID:{id},Path:{file.Path}"); } } }