C# 文件上传到七牛云服务器(二)

49 篇文章 13 订阅

本章讲述:C# 中调用七牛云提供的SDK,实现文件分片上传、支持断点续上传、暂停/继续、进度回调显示

文件简单上传讲解,请查看:C# 文件上传到七牛云服务器(一)

地址为:

开发流程步骤地址:https://blog.csdn.net/BYH371256/article/details/79868562

新建类,存储相关参数,参数注释可参考:C# 文件上传到七牛云服务器(一)

//七牛云默认参数初始化
QiniuEnv QiniuParam = new QiniuEnv();

部分参数定义和辅助类

//上传暂停列表
public List<ControlChanged> UpLoadPauseList = new List<ControlChanged>();
private SyncSetting syncSetting;
private ControlChanged ctrlUpLoad;
public class SyncSetting		// 文件分片相关
{
	//local dir to sync
	public string SyncLocalDir { set; get; }
	//target bucket
	public string SyncTargetBucket { set; get; }
	// file type
	public int FileType { set; get; }
	//check remote duplicate
	public bool CheckRemoteDuplicate { set; get; }
	//prefix
	public string SyncPrefix { set; get; }
	//check new files
	public bool CheckNewFiles { set; get; }
	//ignore dir
	public bool IgnoreDir { set; get; }
	//skip prefixes
	public string SkipPrefixes { set; get; }
	//skip suffixes
	public string SkipSuffixes { set; get; }
	//overwrite same file
	public bool OverwriteFile { set; get; }
	//default chunk size
	public int DefaultChunkSize { set; get; }
	//upload threshold
	public int ChunkUploadThreshold { set; get; }
	//sync thread count
	public int SyncThreadCount { set; get; }
	//upload entry domain
	public int UploadEntryDomain { set; get; }

}

 

public class ControlChanged //: Caliburn.Micro.PropertyChangedBase
{
//继承 Caliburn.Micro,要么写属性更改通知接口
	public ControlChanged()
	{

	}

	public ControlChanged(int nIndex, bool bPause)
	{
		Index = nIndex;
		UpLoadPaused = bPause;
	}

	private int index = 0;
	/// <summary>
	/// 索引
	/// </summary>
	public int Index
	{
		get { return index; }
		set
		{
			index = value;
			NotifyOfPropertyChange(() => Index);
		}
	}

	private bool upLoadPaused = false;
	/// <summary>
	/// 上传控制
	/// </summary>
	public bool UpLoadPaused
	{
		get { return upLoadPaused; }
		set
		{
			upLoadPaused = value;
			NotifyOfPropertyChange(() => UpLoadPaused);
		}
	}

}

分片、断点续传实现

/// <param name="Filekey">索引值 列表中索引号</param>
/// <param name="upLoadFile">文件本地地址</param>
/// <returns></returns>
public string ResumableUpLoading(int Filekey ,string upLoadFile, bool bChunk = false)
{
	syncSetting = new SyncSetting();
	ctrlUpLoad = new ControlChanged();

	string CallBackUrl = "";
	//AK和SK校验 
	Mac mac = new Mac(QiniuParam.AccessKey, QiniuParam.SecretKey);
	string FileName = System.IO.Path.GetFileName(upLoadFile);
	string key = FileName;

	System.IO.Stream fs = System.IO.File.OpenRead(upLoadFile);
	//策略设置
	PutPolicy putPolicy = new PutPolicy();
	putPolicy.Scope = QiniuParam.Bucket + ":" + key;
	putPolicy.SetExpires(3600 * 24);//上传失效
	//putPolicy.DeleteAfterDays = 2;//上传删除  默认不删除
	string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
	//配置
	Config config = new Config();
	config.UseHttps = true;
	config.Zone = Zone.ZONE_CN_South;//服务器 所在地区
	config.UseCdnDomains = true;
	config.ChunkSize =  bChunk == false ? ChunkUnit.U256K :ChunkUnit.U4096K;//U512K   chunkUnit上传分片大小,可选值128KB,256KB,512KB,1024KB,2048KB,4096KB
	ResumableUploader target = new ResumableUploader(config);

	PutExtra extra = new PutExtra();
	//设置断点续传进度记录文件
	extra.ResumeRecordFile = ResumeHelper.GetDefaultRecordKey(upLoadFile, key);
	extra.ResumeRecordFile = FileName + ".progress";

	extra.BlockUploadThreads = this.syncSetting.DefaultChunkSize;
	//获取文件大小
	System.IO.FileInfo fileInfo = new System.IO.FileInfo(upLoadFile);
	long fileLength = fileInfo.Length;
	//上传进度   委托
	UploadProgressHandler progressHandler = new UploadProgressHandler(delegate(long uploadBytes, long totalBytes)
	{
		//Console.WriteLine("progress: " + uploadBytes + ", " + totalBytes);
		double percent = uploadBytes * 1.0 / totalBytes;
		CallProgress(Filekey, upLoadFile, key, fileLength, percent);
	});
	extra.ProgressHandler = progressHandler;
	//暂停  继续
	extra.UploadController = new UploadController(delegate
	{
		foreach (ControlChanged item in UpLoadPauseList)
		{
			if(item.Index == Filekey && !item.UpLoadPaused)
			{
				item.UpLoadPaused = true;
				return UploadControllerAction.Suspended;                        
			}
		}
		return UploadControllerAction.Activated;
	});
	
	//上传
	HttpResult result = target.UploadStream(fs, key, token, extra);
	if (result.Code == 200)
	{
		//返回 下载地址拼接  C# SDK 不会返回完整的url
		CallBackUrl = "http://" + QiniuParam.Domain + "/" + FileName;
		CallUrl(Filekey, upLoadFile, key, fileLength, CallBackUrl);
	}
	else
	{
		CallUrl(Filekey, upLoadFile, key, fileLength, "");
	}

	return CallBackUrl;
}

/// <param name="isPause">是否暂停  true 暂停   false 继续</param>
public void UpLoadPause(int index, bool isPause)
{
	if (isPause)
	{
		if (!UpLoadPauseList.Exists(p => p.Index == index))
		{
			UpLoadPauseList.Add(new ControlChanged(index, false));
		}
	}
	else
	{
		if (UpLoadPauseList.Exists(p => p.Index == index))
		{
			UpLoadPauseList.Remove(UpLoadPauseList.Find(s => s.Index == index));
		}
	}
}

进度回调显示和完成下载地址回调

public delegate int Progress(int taskId, string fileFullPath, string fileKey, long fileLength, double percent);
public Progress OnProgress = null;
public void SetProgressCallBack(Progress Progress)
{
	this.OnProgress = Progress;
}

//索引、上传文件地址、文件名称、文件大小、文件百分比
public void CallProgress(int taskId, string fileFullPath, string fileKey, long fileLength, double percent)
{
	if (OnProgress != null)
	{
		OnProgress(taskId, fileFullPath, fileKey, fileLength, percent);
	}
}  

public delegate int DownLoadUrl(int taskId, string fileFullPath, string fileKey, long fileLength, string Url);
public DownLoadUrl OnDownLoadUrl = null;
public void SetDownLoadUrlCallBack(DownLoadUrl Url)
{
	this.OnDownLoadUrl = Url;
}

public void CallUrl(int taskId, string fileFullPath, string fileKey, long fileLength, string Url)
{
	if (OnDownLoadUrl != null)
	{
		OnDownLoadUrl(taskId, fileFullPath, fileKey, fileLength, Url);
	}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值