public static void MyUpload(string path) { Debug.Log(path); if (string.IsNullOrEmpty(path)) { return; } PutPolicy policy = new PutPolicy(qiniuBucket, 3600); string upToken = policy.Token(); string key = SystemInfo.deviceUniqueIdentifier + "_" + System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + Path.GetFileName(path); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); ResumablePut client = new ResumablePut(setting, extra); CallRet callRet = client.PutFile(upToken, path, key); ReturnBody returnBody = JsonConvert.DeserializeObject <ReturnBody>(callRet.Response); qiniufileName = returnBody.key; Debug.Log(qiniufileName); Debug.Log(callRet.Response); Debug.Log(callRet.Exception); Debug.Log(callRet.StatusCode); }
/// <summary> /// 得到上传文件策略信息 /// </summary> /// <param name="opsParam">上传信息</param> /// <param name="func"></param> public string GetUploadCredentials(UploadPersistentOpsParam opsParam, Func <string> func) { SetPutPolicy(opsParam.Key, opsParam.UploadPersistentOps.IsAllowOverlap, opsParam.UploadPersistentOps.PersistentOps); PutPolicy.CallbackBody = func?.Invoke(); return(Auth.CreateUploadToken(Mac, PutPolicy.ToJsonString())); }
public static void uploadWithFop() { Mac mac = new Mac(Settings.AccessKey, Settings.SecretKey); string bucket = "TARGET_BUCKET"; string saveKey = "SAVE_KEY"; string localFile = "LOCAL_FILE"; // 如果想要将处理结果保存到SAVEAS_BUCKET空间下,文件名为SAVEAS_KEY // 可以使用savas参数 <FOPS>|saveas/<encodedUri> // encodedUri = StringUtils.urlSafeBase64Encode("SAVEAS_BUCKET" + ":" + "SAVEAS_KEY"); string fops = "FOPS"; PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = bucket; putPolicy.PersistentOps = fops; putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = 1; string token = Auth.createUploadToken(putPolicy, mac); FormUploader fm = new FormUploader(); fm.uploadFile(localFile, saveKey, token, null, null); }
/// <summary> /// 简单上传-上传小文件 (根据路径上传图片) /// </summary> /// <param name="localFile">本地文件</param> /// <param name="prefix">前缀</param> /// <param name="saveKey">保存路径</param> /// <returns></returns> public static string uploadFile(string localFile, string prefix, string saveKey) { // 生成(上传)凭证时需要使用此Mac // 这个示例单独提供了一个Settings类,其中包含AccessKey和SecretKey // 实际应用中,请自行设置您的AccessKey和SecretKey Mac mac = new Mac(Settings.AccessKey, Settings.SecretKey); // 上传策略,参见 // http://developer.qiniu.com/article/developer/security/put-policy.html PutPolicy putPolicy = new PutPolicy(); // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // putPolicy.Scope = bucket + ":" + saveKey; putPolicy.Scope = Settings.Bucket; // 上传策略有效期(对应于生成的凭证的有效期) putPolicy.setExpires(3600); // 上传到云端多少天后自动删除该文件,如果不设置(即保持默认)则不删除 //putPolicy.DeleteAfterDays = 1; // 生成上传凭证,参见 // http://developer.qiniu.com/article/developer/security/upload-token.html string token = Auth.createUploadToken(mac, putPolicy.ToJsonString()); FormUploader su = new FormUploader(); HttpResult result = su.uploadFile(localFile, prefix + "/" + saveKey, token); //判断是否上传成功,上传成功,返回路径,否则返回空值 if (result.Code != 200) { return(""); } return(Settings.HostAddress + prefix + "/" + saveKey); }
public void ResumablePutFileTest() { Settings putSetting = new Settings(); // TODO: 初始化为适当的值 string key=NewKey; ResumablePutExtra extra = new ResumablePutExtra(); extra.Notify += new EventHandler<PutNotifyEvent>(extra_Notify); extra.NotifyErr += new EventHandler<PutNotifyErrorEvent>(extra_NotifyErr); extra.Bucket = Bucket; ResumablePut target = new ResumablePut(putSetting, extra); // TODO: 初始化为适当的值 Console.WriteLine ("extra.Bucket:"+extra.Bucket); string upToken = new PutPolicy(extra.Bucket).Token(new Qiniu.Auth.digest.Mac()); target.Progress += new Action<float>(target_Progress); TmpFIle file=new TmpFIle(1024*1024*4); target.PutFinished += new EventHandler<CallRet> ((o,e) => { file.Del (); if (e.OK) { RSHelper.RSDel (Bucket, key); } }); target.PutFile (upToken, file.FileName, key); //Action a = new Action (() => //{ // target.PutFile (upToken, BigFile, NewKey); //}); //a.BeginInvoke (null,null); }
/// <summary> /// 上传文件到七牛云 /// </summary> /// <param name="imgPath">文件路径</param> /// <param name="name">文件后缀名</param> /// <returns>服务器文件路径</returns> public static string UploadFile(string imgPath, string name = ".jpg") { Mac mac = new Mac("h-0RX_DYCsRy3d8NITyVejjVWDXJbVyolHgPQ5xA", "gnTJ6QzZe5tVSZvTrlQLhYs0hZ-Oava2n8FcJtgs"); // 上传文件名 string key = string.IsNullOrEmpty(name) ? Guid.NewGuid().ToString() : Guid.NewGuid().ToString() + name; // 本地文件路径 //string filePath = imgUrl; // 存储空间名 string Bucket = "fyzsmanager"; // 设置上传策略,详见:https://developer.qiniu.com/kodo/manual/1206/put-policy PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = Bucket; putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = 60;//60天后自动删除 string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); Config config = new Config(); // 设置上传区域 config.Zone = Zone.ZONE_CN_South; // 设置 http 或者 https 上传 config.UseHttps = true; config.UseCdnDomains = true; config.ChunkSize = ChunkUnit.U512K; // 表单上传 FormUploader target = new FormUploader(config); HttpResult result = target.UploadFile(imgPath, key, token, null); if (result.Code == 200) { return(string.Format("http://oxdwc8csx.bkt.clouddn.com/{0}", key)); } return(null); }
/// <summary> /// 上传数据流(NetStream) /// </summary> public static void uploadNetStream() { try { string url = "http://img.ivsky.com/img/tupian/pre/201610/09/beifang_shanlin_xuejing-001.jpg"; var wReq = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest; var resp = wReq.GetResponse() as System.Net.HttpWebResponse; using (var stream = resp.GetResponseStream()) { Mac mac = new Mac(Settings.AccessKey, Settings.SecretKey); PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = "xuejing-001.jpg"; putPolicy.SetExpires(3600); string jstr = putPolicy.ToJsonString(); string token = Auth.CreateUploadToken(mac, jstr); // 请不要使用UploadManager的UploadStream方法,因为此流不支持查找(无法获取Stream.Length) // 请使用FormUploader或者ResumableUploader的UploadStream方法 FormUploader fu = new FormUploader(); var result = fu.UploadStream(stream, "xuejing-001.jpg", token); Console.WriteLine(result); } } catch (Exception ex) { Console.WriteLine(ex); } }
public void PutTest() { IOClient target = new IOClient(); string key = NewKey; PrintLn(key); PutExtra extra = new PutExtra(); // TODO: 初始化为适当的值 extra.MimeType = "text/plain"; extra.Crc32 = 123; extra.CheckCrc = CheckCrcType.CHECK; extra.Params = new System.Collections.Generic.Dictionary <string, string>(); PutPolicy put = new PutPolicy(Bucket); target.PutFinished += new EventHandler <PutRet>((o, e) => { if (e.OK) { RSHelper.RSDel(Bucket, key); } }); string token = put.Token(); PutRet ret = target.Put(put.Token(), key, StreamEx.ToStream("Hello, Qiniu Cloud!"), extra); Assert.IsTrue(ret.OK, "PutFileTest Failure"); }
public void PutFileTest() { IOClient target = new IOClient(); string key = NewKey; PrintLn(key); PutExtra extra = new PutExtra(); // TODO: 初始化为适当的值 extra.MimeType = "text/plain"; extra.Crc32 = 123; extra.CheckCrc = CheckCrcType.CHECK; extra.Params = new System.Collections.Generic.Dictionary <string, string> (); PutPolicy put = new PutPolicy(Bucket); TmpFIle file = new TmpFIle(1024 * 10); target.PutFinished += new EventHandler <PutRet> ((o, e) => { file.Del(); if (e.OK) { RSHelper.RSDel(Bucket, file.FileName); } }); PutRet ret = target.PutFile(put.Token(), file.FileName, file.FileName, extra); //error params //target.PutFile("error", "error", "error", null); Assert.IsTrue(ret.OK, "PutFileTest Failure"); }
public void uploadStreamTest(string _key, string _filePath) { Mac mac = new Mac(Settings.AccessKey, Settings.SecretKey); UploadManager target = new UploadManager(); string key = _key; string filePath = _filePath; FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = Settings.Bucket + ":" + key; putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = 1; string token = Auth.createUploadToken(putPolicy, mac); UploadOptions uploadOptions = null; UpCompletionHandler upCompletionHandler = new UpCompletionHandler(delegate(string fileKey, ResponseInfo respInfo, string response) { }); target.uploadStream(fs, key, token, uploadOptions, upCompletionHandler); }
public override Task SaveAsync(BlobProviderSaveArgs args) { //TODO... var containerName = args.ContainerName; var blobName = $"{args.BlobName}"; var configurationSection = _configuration.GetSection("Qiniu"); Mac mac = new Mac(configurationSection["AccessKey"], configurationSection["SecretKey"]);// AK SK使用 PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = configurationSection["Bucket"]; string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());//token生成 Config config = new Config() { Zone = Zone.ZONE_CN_South, UseHttps = true }; FormUploader upload = new FormUploader(config); HttpResult result = new HttpResult(); Stream stream = args.BlobStream; result = upload.UploadStream(stream, blobName, token, null); if (result.Code != 200) { throw new Exception(result.RefText);//上传失败错误信息 } return(Task.CompletedTask); }
public void UpLoadToQiNiu(Stream stream, string path) { IOClient target = new IOClient(); PutExtra extra = new PutExtra(); //普通上传,只需要设置上传的空间名就可以了,第二个参数可以设定token过期时间 PutPolicy put = new PutPolicy(bucket, 3600); //调用Token()方法生成上传的Token string upToken = put.Token(); //上传文件的路径 //String filePath = "/.../..."; var _path = EnsureUrlSeparatorChar(path); //上传 将umbraco的path作为key传入 PutRet ret = target.Put(upToken, _path, stream, extra); LogHelper.Info <PutRet>("上传至七牛云" + (ret.OK ? "成功" : "失败")); if (ret.OK) { } else { throw new Exception("上传失败"); } }
public void uploadStreamTest() { try { Mac mac = new Mac(Settings.AccessKey, Settings.SecretKey); UploadManager target = new UploadManager(); string key = "s" + SmartHeatStationParaInfo.TimeHelper.GetUpLoadTime() + ".txt"; string filePath = "stations.txt"; FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = Settings.Bucket + ":" + key; putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = 1; string token = Auth.createUploadToken(putPolicy, mac); UploadOptions uploadOptions = null; UpCompletionHandler upCompletionHandler = new UpCompletionHandler(delegate(string fileKey, ResponseInfo respInfo, string response) { }); target.uploadStream(fs, key, token, uploadOptions, upCompletionHandler); } catch { } }
public void PutFileWithoutKeyTest() { IOClient target = new IOClient(); string key = NewKey; PrintLn (key); PutExtra extra = new PutExtra (); // TODO: 初始化为适当的值 extra.MimeType = "text/plain"; extra.Crc32 = 123; extra.CheckCrc = CheckCrcType.CHECK; extra.Params = new System.Collections.Generic.Dictionary<string, string> (); PutPolicy put = new PutPolicy (Bucket); TmpFIle file = new TmpFIle (1024 * 10); target.PutFinished += new EventHandler<PutRet> ((o,e) => { file.Del (); if (e.OK) { RSHelper.RSDel (Bucket, file.FileName); } }); PutRet ret = target.PutFileWithoutKey (put.Token (),file.FileName, extra); //error params //target.PutFile("error", "error", "error", null); Assert.IsTrue (ret.OK, "PutFileTest Failure"); }
/// <summary> /// 删除云端图片 /// </summary> /// <param name="filename">文件名称</param> /// <returns></returns> public static CloudFile GetToken() { var model = new CloudFile(); try { Mac mac = new Mac(Ak, Sk); // 上传策略,参见 // https://developer.qiniu.com/kodo/manual/put-policy PutPolicy putPolicy = new PutPolicy(); // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // putPolicy.Scope = bucket + ":" + saveKey; putPolicy.Scope = Bucket; // 上传策略有效期(对应于生成的凭证的有效期) putPolicy.SetExpires(3600); // 上传到云端多少天后自动删除该文件,如果不设置(即保持默认默认)则不删除 //putPolicy.DeleteAfterDays = 1; // 生成上传凭证,参见 // https://developer.qiniu.com/kodo/manual/upload-token string jstr = putPolicy.ToJsonString(); string token = Auth.CreateUploadToken(mac, jstr); model.Token = token; model.Page = BasePath; } catch (Exception ex) { model.Code = 500; model.Message = ex.Message; } return(model); }
public string GetToken() { var applicationKey = AppSettings.QiNiuConfig.ApplicationKey; var mac = new Mac(applicationKey, AppSettings.QiNiuConfig.SecretKey); var bucket = AppSettings.QiNiuConfig.Bucket; var putPolicy = new PutPolicy { Scope = bucket }; Config.AutoZone(applicationKey, bucket, useHTTPS: true); // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // putPolicy.Scope = bucket + ":" + saveKey; // 上传策略有效期(对应于生成的凭证的有效期) putPolicy.SetExpires(3600); // 上传到云端多少天后自动删除该文件,如果不设置(即保持默认默认)则不删除 //putPolicy.DeleteAfterDays = 1; // 生成上传凭证,参见 // https://developer.qiniu.com/kodo/manual/upload-token var jstr = putPolicy.ToJsonString(); var token = Auth.CreateUploadToken(mac, jstr); return(token); }
/// <summary> /// 简单上传-上传字节数据 /// </summary> public static string UploadData(string saveKey, byte[] data) { string fileUrl = string.Empty; // 生成(上传)凭证时需要使用此Mac Mac mac = new Mac(AK, SK); string bucket = imageBucket; ZoneID zoneId = ZoneID.CN_South; Qiniu.Common.Config.SetZone(zoneId, false); // 上传策略,参见 // https://developer.qiniu.com/kodo/manual/put-policy PutPolicy putPolicy = new PutPolicy(); // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // putPolicy.Scope = bucket + ":" + saveKey; putPolicy.Scope = bucket; // 上传策略有效期(对应于生成的凭证的有效期) putPolicy.SetExpires(3600); // 上传到云端多少天后自动删除该文件,如果不设置(即保持默认默认)则不删除 //putPolicy.DeleteAfterDays = 1; // 生成上传凭证,参见 // https://developer.qiniu.com/kodo/manual/upload-token string jstr = putPolicy.ToJsonString(); string token = Auth.CreateUploadToken(mac, jstr); FormUploader fu = new FormUploader(); HttpResult result = fu.UploadData(data, saveKey, token); // Console.WriteLine(result); fileUrl = domain + saveKey; return(fileUrl); }
public Video InsertVideo(byte[] videoBinary, string extension, string mimeType, string seoFilename, bool isNew = true) { string saveKey = Guid.NewGuid().ToString() + extension; PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = bucket + ":" + saveKey; putPolicy.SetExpires(3600); putPolicy.InsertOnly = 1; string jstr = putPolicy.ToJsonString(); string token = Auth.CreateUploadToken(mac, jstr); UploadManager um = new UploadManager(); HttpResult result = um.UploadData(videoBinary, saveKey, token); var video = new Video { VideoUrl = saveKey, MimeType = mimeType, SeoFilename = seoFilename, IsNew = isNew, }; _videoRepository.Insert(video); _eventPublisher.EntityInserted(video); return(video); }
public async Task DeleteBlob_Test(string containerName, string blobName) { var bucketsResult = qiNiuStorageProvider.BucketManager.Buckets(true); //由于没有提供创建空间的API,请去管理后台手动创建 bucketsResult.Result.Contains(containerName).ShouldBe(true); await Assert.ThrowsAnyAsync <StorageException>(async() => await StorageProvider.DeleteBlob(containerName, blobName) ); var putPolicy = new PutPolicy { Scope = containerName }; putPolicy.SetExpires(120); putPolicy.DeleteAfterDays = 1; var token = Auth.CreateUploadToken(qiNiuStorageProvider.Mac, putPolicy.ToJsonString()); var um = new UploadManager(qiNiuStorageProvider.Config); var testFilePath = Path.Combine(localPath, blobName); File.WriteAllText(testFilePath, GetTestContent()); var result = um.UploadFile(testFilePath, blobName, token, new PutExtra() { }); if (result.Code == 200) { await StorageProvider.DeleteBlob(containerName, blobName); } }
public void UploadFileTest() { Mac mac = new Mac(AccessKey, SecretKey); Random rand = new Random(); string key = string.Format("UploadFileTest_{0}.dat", rand.Next()); string filePath = LocalFile; PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = Bucket + ":" + key; putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = 1; string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); Config config = new Config(); config.Zone = Zone.ZONE_CN_East; config.UseHttps = true; config.UseCdnDomains = true; config.ChunkSize = ChunkUnit.U512K; FormUploader target = new FormUploader(config); HttpResult result = target.UploadFile(filePath, key, token, null); Console.WriteLine("form upload result: " + result.ToString()); Assert.AreEqual((int)HttpCode.OK, result.Code); }
/// <summary> /// /// </summary> public BaseStorageProvider(ILogService logService, QiNiuStorageConfig qiNiuConfig) { _logService = logService; QiNiuConfig = qiNiuConfig; new QiNiuConfigValidator().Validate(qiNiuConfig).Check(); Mac = new Mac(QiNiuConfig.AccessKey, QiNiuConfig.SecretKey); #region 策略 PutPolicy = new PutPolicy(); #region 成功后通知 if (!string.IsNullOrEmpty(QiNiuConfig.CallbackBody)) { PutPolicy.PersistentNotifyUrl = QiNiuConfig.PersistentNotifyUrl; PutPolicy.CallbackBody = QiNiuConfig.CallbackBody; PutPolicy.CallbackBodyType = QiNiuConfig.CallbackBodyType.GetDescription(); PutPolicy.CallbackUrl = QiNiuConfig.CallbackUrl; } if (!string.IsNullOrEmpty(QiNiuConfig.PersistentPipeline)) { PutPolicy.PersistentPipeline = QiNiuConfig.PersistentPipeline; } #endregion #endregion }
public static string GenerateToken() { string AK = ""; string SK = ""; // ZoneID zoneId = ZoneID.CN_East; // [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美] // USE_HTTPS = (true|false) 是否使用HTTPS Config.SetZone(ZoneID.CN_North, false); // 上传策略,参见 // https://developer.qiniu.com/kodo/manual/put-policy PutPolicy putPolicy = new PutPolicy(); // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // putPolicy.Scope = bucket + ":" + saveKey; putPolicy.Scope = bucket; // 上传策略有效期(对应于生成的凭证的有效期) putPolicy.SetExpires(3600); // 上传到云端多少天后自动删除该文件,如果不设置(即保持默认默认)则不删除 //putPolicy.DeleteAfterDays = 1; Mac mac = new Mac(AK, SK); macKey = mac; Auth auth = new Auth(mac); string token = auth.CreateUploadToken(putPolicy.ToJsonString()); return(token); }
public async Task UploadFileTest() { var mac = new Mac(AccessKey, SecretKey); var rand = new Random(); var key = $"UploadFileTest_{rand.Next()}.dat"; var filePath = LocalFile; var putPolicy = new PutPolicy { Scope = Bucket + ":" + key, DeleteAfterDays = 1 }; putPolicy.SetExpires(3600); var token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); var config = new Config { Zone = Zone.ZoneCnEast, UseHttps = true, UseCdnDomains = true, ChunkSize = ChunkUnit.U512K }; var target = new ResumableUploader(config); var result = await target.UploadFile(filePath, key, token, null); Console.WriteLine("chunk upload result: " + result); Assert.Equal((int)HttpCode.OK, result.Code); }
public async Task <HttpResult> UploadStream(Stream stream, PutPolicy putPolicy, string key, PutExtra putExtra) { var token = _auth.CreateUploadToken(putPolicy.ToJsonString()); var result = await _formUploader.UploadStream(stream, key, token, putExtra); return(result); }
public static string PutFile(string bucket, string key, Stream stream) { try { var scope = bucket + ":" + key; var policy = new PutPolicy(scope); string upToken = policy.Token(); var extra = new PutExtra(); var client = new IOClient(); var ret = client.Put(upToken, key, stream, extra); if (ret.OK) { return(string.Format(ConfigUtility.GetValue("QiNiuDomain"), bucket) + ret.key); } else { return(""); } } catch (Exception e) { log4net.LogManager.GetLogger("ImageUpload").Error(e.Message); return(""); } }
/// <summary> /// 图片上传到七牛 /// </summary> /// <param name="filename"></param> /// <param name="data"></param> /// <returns></returns> private static ItemResult <string> UploadQiNiu(string filename, byte[] data) { ItemResult <string> res = new ItemResult <string>(); Mac mac = new Mac(ApplicationContext.AppSetting.QiNiu_AccessKey, ApplicationContext.AppSetting.QiNiu_SecretKey); // 设置上传策略,详见:https://developer.qiniu.com/kodo/manual/1206/put-policy PutPolicy putPolicy = new PutPolicy(); // 设置要上传的目标空间 putPolicy.Scope = ApplicationContext.AppSetting.QiNiu_Bucket; // 上传策略的过期时间(单位:秒) putPolicy.SetExpires(3600); // 文件上传完毕后,在多少天后自动被删除 putPolicy.DeleteAfterDays = 1; // 生成上传token string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); Qiniu.Storage.Config config = new Qiniu.Storage.Config(); // 设置上传区域 config.Zone = Zone.ZONE_CN_East; // 设置 http 或者 https 上传 config.UseHttps = true; config.UseCdnDomains = true; config.ChunkSize = ChunkUnit.U512K; // 表单上传 FormUploader target = new FormUploader(config); Qiniu.Http.HttpResult result = target.UploadData(data, filename, token, null); res.Data = JsonConvert.DeserializeObject <QiniuOss>(result.Text).key; res.Success = true; return(res); }
public APIResult UploadAvatar(UploadAvatarInput input) { APIResult result = new APIResult(true); var file = input.avatarFile; // 生成(上传)凭证时需要使用此Mac // 这个示例单独提供了一个Settings类,其中包含AccessKey和SecretKey // 实际应用中,请自行设置您的AccessKey和SecretKey Qiniu.Common.Config.SetZone(Qiniu.Common.ZoneID.CN_South, false); Mac mac = new Mac(APP_KEY, SECRET_KEY); string bucket = "gougouapp"; string saveKey = file.Name; // 上传策略,参见 // http://developer.qiniu.com/article/developer/security/put-policy.html PutPolicy putPolicy = new PutPolicy(); // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // putPolicy.Scope = bucket + ":" + saveKey; putPolicy.Scope = bucket; // 上传策略有效期(对应于生成的凭证的有效期) putPolicy.SetExpires(3600); // 上传到云端多少天后自动删除该文件,如果不设置(即保持默认默认)则不删除 putPolicy.DeleteAfterDays = 1; // 生成上传凭证,参见 // http://developer.qiniu.com/article/developer/security/upload-token.html string jstr = putPolicy.ToJsonString(); string token = Auth.CreateUploadToken(mac, jstr); FormUploader fu = new FormUploader(); // 支持自定义参数 //var extra = new System.Collections.Generic.Dictionary<string, string>(); //extra.Add("FileType", "UploadFromLocal"); //extra.Add("YourKey", "YourValue"); //UploadFile(...,extra) if (file.Length > 0) { using (var stream = new MemoryStream()) { file.CopyTo(stream); var buffer = stream.ToArray(); HttpResult uploadResult = fu.UploadData(buffer, saveKey, token); result.success = uploadResult.Code == 200; } } else { result.success = false; result.message = "请选择需要上传的文件"; } return(result); }
/// <summary> /// 上传图片到七牛 /// </summary> /// <param name="bucket"></param> /// <param name="fileStream"></param> /// <param name="saveKey"></param> /// <returns></returns> private static async Task <bool> UploadStream(string bucket, Stream fileStream, string saveKey) { var res = false; try { var mac = new Mac(_settings.QiniuOption.AccessKey, _settings.QiniuOption.SecretKey); var putPolicy = new PutPolicy { Scope = bucket + ":" + saveKey }; putPolicy.SetExpires(3600); // 上传策略有效期(对应于生成的凭证的有效期) var jstr = putPolicy.ToJsonString(); var token = Auth.CreateUploadToken(mac, jstr); var fu = new FormUploader(); var result = await fu.UploadStreamAsync(fileStream, saveKey, token); if (result.Code == 200) { res = true; } } catch (Exception ex) { _toollogger.LogError("上传图片到云存储异常:异常信息:" + ex); } return(res); }
public void ResumablePutFileTest() { Settings putSetting = new Settings(); // TODO: 初始化为适当的值 string key=NewKey; ResumablePutExtra extra = new ResumablePutExtra(); NameValueCollection nc = new NameValueCollection (); nc.Add("x:username","qiniu"); extra.CallbackParams = nc; extra.Notify += new EventHandler<PutNotifyEvent>(extra_Notify); extra.NotifyErr += new EventHandler<PutNotifyErrorEvent>(extra_NotifyErr); ResumablePut target = new ResumablePut(putSetting, extra); // TODO: 初始化为适当的值 Console.WriteLine ("extra.Bucket:"+Bucket); string upToken = new PutPolicy(Bucket).Token(new Qiniu.Auth.digest.Mac()); TmpFIle file=new TmpFIle(1024*1024*4); target.PutFinished += new EventHandler<CallRet> ((o,e) => { file.Del (); if (e.OK) { RSHelper.RSDel (Bucket, key); } }); CallRet ret =target.PutFile (upToken, file.FileName, key); //Action a = new Action (() => //{ // target.PutFile (upToken, BigFile, NewKey); //}); //a.BeginInvoke (null,null); }
private void upload() { //设置账号的AK和SK Qiniu.Conf.Config.ACCESS_KEY = "Access_Key"; Qiniu.Conf.Config.SECRET_KEY = "Secret_Key"; IOClient target = new IOClient(); PutExtra extra = new PutExtra(); //设置上传的空间 String bucket = "bucket_name"; //设置上传的文件的key值 String key = "yourdefinekey"; //覆盖上传,<bucket>:<key>,表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”,已存在同名资源则会被本次覆盖。 PutPolicy put = new PutPolicy(bucket + ":" + key, 3600); //设置callbackUrl以及callbackBody,七牛将文件名和文件大小回调给业务服务器 put.CallBackUrl = "http://your.domain.com/callback"; put.CallBackBody = "filename=$(fname)&filesize=$(fsize)"; //调用Token()方法生成上传的Token string upToken = put.Token(); //上传文件的路径 String filePath = "/.../..."; //调用PutFile()方法上传 PutRet ret = target.PutFile(upToken, key, filePath, extra); //打印出相应的信息 Console.WriteLine(ret.Response.ToString()); Console.WriteLine(ret.key); Console.ReadLine(); }
/// <summary> /// 视频切片 /// </summary> private static void CutVideo(PutPolicy put, string key, FileTypeDirEnum dir) { var bucket = QiniuUtil.GetServerBucketHlsName(dir); if (bucket == String.Empty) { return; } //设置切片操作参数 String fops = String.Format("avthumb/m3u8/segtime/10/ab/128k/ar/44100/acodec/libfaac/r/30/vb/240k/vcodec/libx264/stripmeta/0/{0}", QiniuConfig.GetWaterText()); //设置切片的队列 string pipeline = "yihui_queue"; //可以对转码后的文件进行使用saveas参数自定义命名,当然也可以不指定文件会默认命名并保存在当前空间。 String urlbase64 = Qiniu.Util.Base64URLSafe.Encode(String.Format("{0}:{1}", bucket, key)); String pfops = fops + "|saveas/" + urlbase64; put.FsizeLimit = 1024 * 1024 * 800; put.PersistentNotifyUrl = QiniuConfig.UploadCallback; put.PersistentOps = pfops; put.PersistentPipeline = pipeline; }
public string GetUploadToken(string type, string imgPara = "", long uid = 0) { string bucket; string domain; GetTokenAndDomain(type, out bucket, out domain); string entryKey = DESEncrypt.Encrypt(GetEncryptText(DateTime.Now)); PutPolicy put = new PutPolicy(bucket, 8 * 60 * 60); put.CallBackUrl = "http://" + callBackUrl + "/api/QiniuUpload/Callback"; string callBackBody = "BusinessType=" + type + "&WOBO=" + entryKey + "&key=$(key)&hash=$(etag)&filesize=$(fsize)"; callBackBody += type.Equals("video") ? "&avinfo=$(avinfo)" : "&imageInfo=$(imageInfo)"; if (!string.IsNullOrEmpty(imgPara)) { callBackBody += "&imgPara=" + imgPara; } if (uid >= 1) { callBackBody += "&userId=" + uid; } put.CallBackBody = callBackBody; return(put.Token()); }
/// <summary> /// 七牛上传文件 /// </summary> /// <param name="filePath">文件本地路径</param> /// <param name="fileName">文件名称</param> public static int UploadFile(string filePath, string fileName) { Mac mac = new Mac(FileConfig.AccessKey, FileConfig.SecretKey); // 本地文件路径 // 存储空间名 string Bucket = FileConfig.Bucket; // 设置上传策略,详见:https://developer.qiniu.com/kodo/manual/1206/put-policy var putPolicy = new PutPolicy(); // 设置要上传的目标空间 putPolicy.Scope = Bucket; // 上传策略的过期时间(单位:秒) putPolicy.SetExpires(3600); // 文件上传完毕后,在多少天后自动被删除 //putPolicy.DeleteAfterDays = 1; // 生成上传token string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); Config config = new Config(); // 设置上传区域 config.Zone = Zone.ZONE_CN_South; // 设置 http 或者 https 上传 config.UseHttps = true; config.UseCdnDomains = true; config.ChunkSize = ChunkUnit.U4096K; // 表单上传 FormUploader target = new FormUploader(config); var result = target.UploadFile(filePath, fileName, token, null); return(result.Code); }
public void PutPolicyTest(){ PutPolicy policy = new PutPolicy ("lskjd:lskd"); policy.CallBackUrl = "callbackUrl.com"; policy.ReturnUrl = "returnUrl.com"; bool exp = false; try{ policy.Token (); }catch{ exp = true; Assert.IsTrue (true, "PutPolicyTest Failure1"); } Assert.IsTrue (exp, "PutPolicyTest Failure2"); exp = false; policy = new PutPolicy ("bucket"); policy.CallBackUrl = "callbackUrl.com"; try{ policy.Token (); }catch{ exp = true; Assert.IsTrue (true, "PutPolicyTest Failure3"); } Assert.IsTrue (exp, "PutPolicyTest Failure4"); exp = false; policy = new PutPolicy("bucket"); policy.CallBackBody="uid=123"; policy.CallBackUrl="www.qiniu.com"; policy.DetectMime = 1; policy.FsizeLimit=4096; policy.FsizeMin=0; policy.InsertOnly = 1; policy.PersistentNotifyUrl="www.yourdomain.com/persistentNotifyUrl"; policy.PersistentOps = "avthumb/m3u8/preset/video_16x9_440k"; policy.CallbackHost = "180.97.211.38"; policy.CallbackFetchKey = 0; policy.CallbackBodyType = "application/json"; try { string result = policy.ToString(); string expect = "{\"scope\":\"bucket\",\"callBackUrl\":\"www.qiniu.com\",\"callBackBody\":\"uid=123\",\"deadline\":0,\"insertOnly\":1,\"detectMime\":1,\"fsizeLimit\":4096,\"fsizeMin\":0,\"persistentNotifyUrl\":\"www.yourdomain.com/persistentNotifyUrl\",\"persistentOps\":\"avthumb/m3u8/preset/video_16x9_440k\",\"callbackHost\":\"180.97.211.38\",\"callbackBodyType\":\"application/json\",\"callbackFetchKey\":0}"; //Assert.IsTrue(result==expect,"PutPolicyTest Failure5"); Assert.AreEqual(result, expect); } catch (Exception ee){ Assert.IsTrue (false, ee.Message.ToString()); } }
public static void PutTest() { IOClient target = new IOClient(); string upToken = string.Empty; string key = LocalKey; //PrintLn(key); PutExtra extra = new PutExtra(); // TODO: 初始化为适当的值 extra.MimeType = "text/plain"; extra.Crc32 = 123; extra.CheckCrc = CheckCrcType.CHECK; extra.Params = new System.Collections.Generic.Dictionary<string, string>(); extra.Scope = Bucket+":"+key; PutPolicy put = new PutPolicy(extra.Scope); PutRet ret = target.Put(put.Token(), key, "hello Qiniu Cloud!".ToStream(), extra); //Assert.IsTrue(ret.OK, "PutFileTest Failure"); }
public static List<string> RSPut(string bucket,int num) { IOClient target = new IOClient(); string key = "csharp" + Guid.NewGuid().ToString(); //PrintLn(key); PutExtra extra = new PutExtra(); // TODO: 初始化为适当的值 extra.MimeType = "text/plain"; PutPolicy put = new PutPolicy(bucket); List<string> newKeys=new List<string>(); for (int i=0; i<num; i++) { key = "csharp" + Guid.NewGuid ().ToString (); PutRet ret = target.Put (put.Token (), key,StreamEx.ToStream("Hello, Qiniu Cloud!"), extra); if (ret.OK) { newKeys.Add (key); } } return newKeys; }
public void PutPolicyTest() { PutPolicy policy = new PutPolicy ("lskjd:lskd"); policy.CallBackUrl = "callbackUrl.com"; policy.ReturnUrl = "returnUrl.com"; bool exp = false; try{ policy.Token (); }catch{ exp = true; Assert.IsTrue (true, "PutPolicyTest Failure"); } Assert.IsTrue (exp, "PutPolicyTest Failure"); exp = false; policy = new PutPolicy ("bucket"); policy.CallBackUrl = "callbackUrl.com"; try{ policy.Token (); }catch{ exp = true; Assert.IsTrue (true, "PutPolicyTest Failure"); } Assert.IsTrue (exp, "PutPolicyTest Failure"); exp = false; policy = new PutPolicy("bucket"); policy.AsyncOps=""; policy.CallBackBody="uid=123"; policy.CallBackUrl="www.qiniu.com"; policy.DetectMime = 1; policy.FsizeLimit=4096; policy.InsertOnly = 1; policy.PersistentNotifyUrl="www.yourdomain.com/persistentNotifyUrl"; policy.PersistentOps = "avthumb/m3u8/preset/video_16x9_440k"; try { string result = policy.ToString(); string expect = "{\"scope\":\"bucket\",\"callBackUrl\":\"www.qiniu.com\",\"callBackBody\":\"uid=123\",\"asyncOps\":\"\",\"deadline\":0,\"insertOnly\":1,\"detectMime\":1,\"fsizeLimit\":4096,\"persistentNotifyUrl\":\"www.yourdomain.com/persistentNotifyUrl\",\"persistentOps\":\"avthumb/m3u8/preset/video_16x9_440k\"}"; Assert.IsTrue(result==expect,"PutPolicyTest Failure"); } catch (Exception ee){ Assert.IsTrue (false, "PutPolicyTest Failure"); } }
public void PutTest() { IOClient target = new IOClient(); string key = NewKey; PrintLn(key); PutExtra extra = new PutExtra(); // TODO: 初始化为适当的值 extra.MimeType = "text/plain"; extra.Crc32 = 123; extra.CheckCrc = CheckCrcType.CHECK; extra.Params = new System.Collections.Generic.Dictionary<string, string>(); PutPolicy put = new PutPolicy(Bucket); target.PutFinished += new EventHandler<PutRet>((o, e) => { if (e.OK) { RSHelper.RSDel(Bucket, key); } }); string token = put.Token(); PutRet ret = target.Put(put.Token(), key, StreamEx.ToStream("Hello, Qiniu Cloud!"), extra); Assert.IsTrue(ret.OK, "PutFileTest Failure"); }
public HttpResponseMessage UpToken() { Debug.WriteLine("UpToken"); PutPolicy put = new PutPolicy(bucket); put.CallBackUrl = "http://wobo.ylhyh.onmypc.net:810/QiniuSample/api/Video/Callback"; //refer to http://developer.qiniu.com/docs/v6/api/overview/up/response/vars.html for available variables //refer to http://developer.qiniu.com/docs/v6/api/reference/fop/av/avinfo.html //put.CallBackBody = "name=$(fname)&UploadType=$(x:UploadType)&key=$(key)&hash=$(etag)&filesize=$(fsize)&avinfo=$(avinfo)"; put.CallBackBody = "name=$(fname)&UploadType=avatar&key=$(key)&hash=$(etag)&filesize=$(fsize)&avinfo=$(avinfo)"; HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent("{\"uptoken\":\"" + put.Token() + "\"}", Encoding.UTF8, "application/json"); return response; }