using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; namespace MEAS.Common { public class FileHelper { //定义一个用于保存静态变量的实例 private static FileHelper instance = null; //定义一个保证线程同步的标识 private static readonly object locker = new object(); //构造函数为私有,使外界不能创建该类的实例 public static FileHelper Instance { get { if (instance == null) { lock (locker) { if (instance == null) instance = new FileHelper(); } } return instance; } } /// 服务器文件下载 /// </summary> /// <param name="url">服务器下载文件地址</param> /// <param name="filepath">文件存放地址,包含文件名</param> /// <returns></returns> public string DownLoadFile(string fileUrl, string filepath) { try { using (WebClient client = new WebClient()) { client.DownloadFile(fileUrl, filepath); } } catch (Exception) { throw; } return filepath; } /// <summary> /// 文件上传 /// </summary> /// <param name="files">文件集合</param> /// <returns></returns> public string UploadFile(List<IFormFile> files) { string dir = string.Empty; string fileName = string.Empty; string targetPath = string.Empty; long size = files.Sum(f => f.Length); foreach (IFormFile formFile in files) { if (formFile.Length > 0) { var filePath = Path.GetTempFileName(); dir = AppDomain.CurrentDomain.BaseDirectory + "\\ExcelTemplate\\FileUpload\\"; fileName = DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss") +" "+ formFile.FileName; targetPath = dir + "\\" + fileName; //文件全路径(e:\abc.txt) using (var stream = System.IO.File.Create(targetPath)) { formFile.CopyToAsync(stream); } } } return targetPath; } /// http下载文件 /// </summary> /// <param name="url">服务器下载文件地址</param> /// <param name="path">文件存放地址,包含文件名</param> /// <returns></returns> private string HttpDownloadFile(string url, string path) { try { // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); //创建本地文件写入流 Stream stream = new FileStream(path, FileMode.Create); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { stream.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } stream.Close(); responseStream.Close(); return path; } catch (Exception) { throw; } } } }
参考:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/file-uploads?view=aspnetcore-6.0