在.net core中,利用C#實作fastdfs多檔案批量上傳
/// <summary>
/// 上傳附件
/// </summary>
/// <returns></returns>
[RequestSizeLimit(1073741824)]
[HttpPost]
[Route("FileUpLoad")]
public ActionResult<IEnumerable<string>> UpLoadFile([FromForm]IFormCollection formCollection, string id)
{
try
{
bool flag = false;
//擷取FormData中多檔案資訊
Microsoft.AspNetCore.Http.Internal.FormFileCollection filelist = (FormFileCollection)formCollection.Files;
foreach (var item in filelist)
{
if (item != null)
{
var storageNode = FileServerInit.GetStorageNode();
string type = item.FileName.Split(".").Last();
byte[] content = null;
//将檔案轉換為位元組流
Stream fs = item.OpenReadStream();
using (BinaryReader reader = new BinaryReader(fs))
{
content = reader.ReadBytes((int)fs.Length);
}
string fileSize = FileServerInit.GetFileSize(content.Length);
string filePath = FastDFSClient.UploadFile(storageNode, content, type);
//........
}
}
//傳回結果
}
catch (Exception e)
{
//異常處理
}
}
//檔案初始化
public class FileServerInit
{
/// <summary>
/// 擷取存儲節點
/// </summary>
/// <returns></returns>
public static StorageNode GetStorageNode()
{
//===========================初始化========================================
var trackerIPs = new List<IPEndPoint>();
// 隻能指定IP,設定域名需要其他方式作為轉換
string IP = FileServer.GetFileServerIpAddress();
var endPoint = new IPEndPoint(IPAddress.Parse(IP), 22122);
trackerIPs.Add(endPoint);
ConnectionManager.Initialize(trackerIPs);
return FastDFSClient.GetStorageNode("group1");
}
//擷取檔案大小
public static string GetFileSize(long size)
{
var num = 1024.00; //byte
if (size < num)
return size + "B";
if (size < Math.Pow(num, 2))
return (size / num).ToString("f2") + "KB"; //kb
if (size < Math.Pow(num, 3))
return (size / Math.Pow(num, 2)).ToString("f2") + "MB"; //M
if (size < Math.Pow(num, 4))
return (size / Math.Pow(num, 3)).ToString("f2") + "G"; //G
return (size / Math.Pow(num, 4)).ToString("f2") + "TB"; //T
}
}