在.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
}
}