七牛云上传 图片
接口上传
简单示例
包管理器(NuGet)方式安装
或者从NuGet来安装,以Visual Studio 2013/2015为例(如果您的Visual Studio没有安装NuGet,请先安装)。打开NuGet程序包管理器搜索Qiniu.Shared或者在控制台中键入以下命令:
拷贝Install-Package Qiniu.Shared
然后代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Qiniu.Util;
using Qiniu.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Qiniu.JSON;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Http;
public static string AK = "P0fjv0OlY7*********QbkCN1U8GX"; public static string SK = "2EYJgm2k************N_QeMN78tJskV";
protected void Page_Load(object sender, EventArgs e)
{
Mac mac = new Mac(AK, SK);
Auth auth = new Auth(mac);
ZoneID zoneId = ZoneID.US_North;
// [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
// USE_HTTPS = (true|false) 是否使用HTTPS
Qiniu.Common.Config.SetZone(zoneId,false);
Qiniu.JSON.JsonHelper.JsonSerializer = new AnotherJsonSerializer();
Qiniu.JSON.JsonHelper.JsonDeserializer = new AnotherJsonDeserializer();
}
public void UploadFile()
{
// 生成(上传)凭证时需要使用此Mac
// 这个示例单独使用了一个Settings类,其中包含AccessKey和SecretKey
// 实际应用中,请自行设置您的AccessKey和SecretKey
Mac mac = new Mac(AK, SK);
string bucket = "njc123";
string saveKey = "123456.jpg";
string localFile = "F:\\costweb\\costmy\\costmy\\images\\123456.jpg";
// 上传策略,参见
// 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);
UploadManager um = new UploadManager();
HttpResult result = um.UploadFile(localFile, saveKey, token);
Console.WriteLine(result);
Image1.ImageUrl = "http://oo3gzay6z.bkt.gdipper.com/" + saveKey;
TextBox1.Text = result.ToString();
}
public class AnotherJsonSerializer : IJsonSerializer
{
// 实现此接口的JSON序列化方法
public string Serialize<T>(T obj) where T : new()
{
var settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.NullValueHandling = NullValueHandling.Ignore;
return JsonConvert.SerializeObject(obj, settings);
}
}
public class AnotherJsonDeserializer : IJsonDeserializer
{
// 实现此接口的JSON反序列化方法
public bool Deserialize<T>(string str, out T obj) where T : new()
{
obj = default(T);
bool ok = true;
try
{
obj = JsonConvert.DeserializeObject<T>(str);
}
catch (System.Exception)
{
ok = false;
}
return ok;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
UploadFile();
}
根据例子 可以改编,传入对应名称和物理路径 即可上传