客戶端:
復制代碼 代碼如下:
/// <summary>
/// 寫入數據到流中
/// </summary>
/// <param name="url"></param>
/// <param name="callback"></param>
public async static Task<bool> Write(string url, Stream clientStream)
{
if (clientStream.Length > 25*1024*1024)
url += "&t=1"; // 表示上傳大文件
try
{
Up(url, clientStream);
return true;
}
catch { }
return false;
}
public async static Task Up(string url, Stream sourceStream)
{
var wc = new WebClient();
byte[] buffer = new byte[25*1024*1024];
int bufLen = sourceStream.Read(buffer, 0, buffer.Length);
if (bufLen < 1)
{
sourceStream.Close();
return;
}
wc.WriteStreamClosed += (s, e) =>
{
if (sourceStream.CanRead)
Up(url, sourceStream);
else
sourceStream.Close();
};
var serverStream = await wc.OpenWriteTaskAsync(url, "POST");
serverStream.Write(buffer, 0, bufLen);
serverStream.Close();
}
服務端:
復制代碼 代碼如下:
private void Save()
{
string data = Context.Request.QueryString["data"].Base64StringDecode("ABC");
if (data.IsNullOrEmpty())
return;
var m = JsonConvert.DeserializeObject<FileUploadModel>(data);
if (m == null)
return;
var isSplitBlock = Context.Request.QueryString["t"]=="1"; //是否分塊上傳
#region 保存文件
// 初始化目錄
string dirPath = Path.Combine(ConfigHelper.UploadPath, m.Dir); // 文件保存路徑
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
// 文件地址
string filePath = Path.Combine(dirPath, m.FileName);
if (!isSplitBlock)
{
if (File.Exists(filePath))
File.Delete(filePath);
}
int bufLen = 0;
byte[] buffer = new byte[4096];
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
fs.Seek(0, SeekOrigin.End);
// 寫入原文件
Stream sr = Context.Request.InputStream;
while ((bufLen = sr.Read(buffer, 0, buffer.Length)) > 0)
fs.Write(buffer, 0, bufLen);
sr.Close();
sr.Dispose();
// 縮略圖
try
{
if (!m.NeedThumbnail)
return;
dirPath = Path.Combine(dirPath, "Small");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
filePath = Path.Combine(dirPath, m.FileName);
if (File.Exists(filePath))
File.Delete(filePath);
using (var pic = GetThumbnail(fs, 300, 300))
{
pic.Save(filePath);
}
}
catch { }
}
#endregion
#region 刪除原文件
// 刪除原文件
if (m.OldFilePath.IsNullOrEmpty())
{
return;
}
try
{
filePath = Path.Combine(ConfigHelper.UploadPath, m.OldFilePath);
if (File.Exists(filePath))
File.Delete(filePath);
if (m.NeedThumbnail)
{
filePath = Path.Combine(ConfigHelper.UploadPath, m.OldThumbnailImagePath);
if (File.Exists(filePath))
File.Delete(filePath);
}
}
catch (Exception ex)
{
}
#endregion
}
分塊上傳注意點:每塊流保存完以後再去讀取下以塊的數據,不然會多塊一起過來會前面的塊流數據會被後面的塊流數據覆蓋;
注重過程的同時注重結果