1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
[HttpPost, HttpGet, HttpOptions, CorsOptions] public IActionResult DownloadSpecifiedOSSFileToStream(string fileName) { if(string.IsNullOrWhiteSpace(fileName)) { return ErrorResult("未获取到将要下载的文件名称!", 111101); } string accessKey = _configuration["Aliyun:CcementOss:AccessKey:Id"]; string secretKey = _configuration["Aliyun:CcementOss:AccessKey:Secret"]; string bucketName = _configuration["Aliyun:CcementOss:BucketName"]; string endpoint = _configuration["Aliyun:CcementOss:Endpoint"]; string downloadFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DownLoadFile/"); if(Directory.Exists(downloadFilename) == false) { Directory.CreateDirectory(downloadFilename); } if(!string.IsNullOrWhiteSpace(accessKey) && !string.IsNullOrWhiteSpace(secretKey) && !string.IsNullOrWhiteSpace(bucketName) && !string.IsNullOrWhiteSpace(endpoint)) { var client = new OssClient(endpoint, accessKey, secretKey); try { var obj = client.GetObject(bucketName, fileName); using(var requestStream = obj.Content) { byte[] buf = new byte[1024]; var fs = System.IO.File.Open(downloadFilename + fileName, FileMode.OpenOrCreate); var len = 0; while((len = requestStream.Read(buf, 0, 1024)) != 0) { fs.Write(buf, 0, len); } fs.Close(); return SuccessResult(fs); } } catch(Exception ex) { LogHelper.WriteErrorLog("下载文件出现异常,异常原因为:" + ex.Message); return ErrorResult("下载文件出现异常,异常原因为:" + ex.Message, 111150); } } else return ErrorResult("阿里云配置文件读取失败,请联系网站管理员!", 111102); }
|