使用上传插件 Web Uploader 上传图片到七牛云(C#)

时间:2022-02-27 13:13:23

之前有写过一篇文章,基于asp.net mvc 封装 Web Uploader 上传插件:

http://www.cnblogs.com/vanteking/p/5623682.html

已经实现的功能有:

封装 my97datepicker 日历插件 :

 @Html.Calendar("time")

封装 ckeditor编辑器:

 @Html.RichTextEditor("CKEDITOR1", new RichTextEditor { Height = 300, ToolBar = RichTextEditorToolBar.Full, Plugins = RichTextEditorPlugins.CKEDITOR, Width = 900 })

使用上传插件 Web Uploader  上传图片到七牛云(C#)

另外还有百度编辑器的封装,只需要改版参数就可以使用了。
ckeditor 里还配合使用了 ckfinder

使用上传插件 Web Uploader  上传图片到七牛云(C#)

今天重点讲下封装的Web Uploader插件,图片可以上传到七牛云和本地。

先上图:

使用上传插件 Web Uploader  上传图片到七牛云(C#)

使用上传插件 Web Uploader  上传图片到七牛云(C#)

使用上传插件 Web Uploader  上传图片到七牛云(C#)

图片上传到七牛云:

                //Qiniu云
var file = Request.Files["file"];
if (file != null && file.InputStream != null && file.ContentLength > )
{
//七牛空间
var qiniuStore = SystemConst.GetRandStore();
//学校
var school = ViewBag._school_ as SchoolLibrary;
//时间戳
var stime = TimeHelper.ConvertDateTimeInt(DateTime.Now);
//原始文件名
var mine = file.FileName.Substring(file.FileName.LastIndexOf("."));
//目标地址
var filePath = "{0}/{1}/{2}{3}".FormatWith(school.Domain, user.ID.GetHashCode(), stime, mine);
//模型
var buket = new Bucket
{
FileType = (UploadFileType)fileType,
stream = file.InputStream,
saveFilePath = filePath,
saveFileName = file.FileName,
bucket = qiniuStore.Space,
PicDomain = qiniuStore.Domain
};
uploadResult = BucketHelper.UploadFile(buket);

删除七牛云图片:

 //人员信息
var user = ViewBag.stu as OStudent;
//域名空间
var qiniuStore = SystemConst.StoreList.FirstOrDefault(m => file.IsNullOrEmpty() == false && file.StartsWith(m.Domain)); if (string.IsNullOrEmpty(file) == true) { _msg = "文件未找到!"; }
else if (qiniuStore != null)
{
if (file.ToLower().Contains(user.ID.GetHashCode().ToString()) == false) { _msg = "没有权限!"; }
else
{
//地址
var saveFilePath = file.Replace(qiniuStore.Domain, "").Trim();
//模型
var buket = new Bucket
{
saveFilePath = saveFilePath,
bucket = qiniuStore.Space,
};
var result = BucketHelper.Delete(buket);
if (result.State == (int)UploadState.Success)
{
_err = false;
}
else
{
_msg = result.ErrorMessage;
}
}
}

还做了一个七牛云的类的封装:

上传:

     /// <summary>
/// 上传文件
/// </summary>
/// <param name="model"></param>
/// <param>FileType 文件类型</para>
/// <param>bucket 目标空间 默认:studystone</para>
/// <param>PicDomain 目标空间对应的默认域名 </para>
/// <param>strSchool 学校二级</para>
/// <param>saveFileName 目标文件名</para>
/// <param>localFile 本地文件(优先)</para>
/// <param>stream 文件流(本地文件存在则,忽略)</para>
/// <returns></returns>
public static UploadResult UploadFile(Bucket model)
{
//结果
var result = new UploadResult { };
//数据
var data = new HttpResult();
//类型
switch (model.FileType)
{
case UploadFileType.Image:
model.mimeLimit = "image/*";
model.fsizeLimit = ;//2M
break;
case UploadFileType.Video:
model.mimeLimit = "video/mp4";
model.fsizeLimit = ;//40M
break;
case UploadFileType.File:
default:
model.mimeLimit = "application/msword;application/vnd.openxmlformats-officedocument.wordprocessingml.document;application/vnd.ms-excel;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;application/pdf;application/vnd.ms-powerpoint;application/x-rar-compressed;application/x-zip-compressed;text/css;text/html;application/x-javascript;application/json;text/plain";
model.fsizeLimit = ;//40M
break;
}
// 上传策略
PutPolicy putPolicy = new PutPolicy();
// 设置要上传的目标空间
putPolicy.Scope = model.bucket;
// 上传策略的过期时间(单位:秒)
putPolicy.SetExpires();
// 文件上传完毕后,在多少天后自动被删除
//putPolicy.DeleteAfterDays = int.MaxValue;
// Use AK & SK here
Mac mac = new Mac(AK, SK);
// 生成上传凭证
string uploadToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
// 开始上传文件
FormUploader um = new FormUploader();
try
{
//目标地址
if (string.IsNullOrEmpty(model.localFile) == false && File.Exists(model.localFile) == true)
{
data = um.UploadFile(model.localFile, model.saveFilePath, uploadToken);
}
else if (model.stream != null)
{
data = um.UploadStream(model.stream, model.saveFilePath, uploadToken);
}
else
{
result.State = UploadState.Unknown;
result.ErrorMessage = "上传文件为空";
return result;
}
//结果判断
switch (data.Code)
{
//上传成功
case :
result.file = new QiniuFile
{
Date = DateTime.Now.ToString("yyyy年MM月dd日"),
Moment = DateTime.Now.ToString("HH:mm tt").Replace("上午", "AM").Replace("下午", "PM"),
FileName = model.saveFilePath.Substring(model.saveFilePath.LastIndexOf("/") + ),
Fsize = ,
Src = model.PicDomain + model.saveFilePath
};
result.State = UploadState.Success;
result.Url = model.PicDomain + model.saveFilePath;
result.OriginFileName = model.saveFilePath.Substring(model.saveFilePath.LastIndexOf("/") + );
break;
case :
result.State = UploadState.TypeNotAllow;
result.ErrorMessage = "不允许的文件格式上传";
break;
case :
result.State = UploadState.TypeNotAllow;
result.ErrorMessage = "文件大小超过限制";
break;
case :
result.State = UploadState.TypeNotAllow;
result.ErrorMessage = "文件已存在";
break;
default:
result.State = UploadState.Unknown;
result.ErrorMessage = "文件上传失败";
break;
}
}
catch (Exception e)
{
result.State = UploadState.Unknown;
result.ErrorMessage = e.Message;
}
return result;
}

获取七牛云图片列表

   /// <summary>
/// 获取空间下面所有的图片
/// </summary>
/// <param name="model"></param>
/// <para>bucket 目标空间默认:stonestudy</para>
/// <para>prefix 按文件名前缀保留搜索结果 如:ss/</para>
/// <para>limit 每次最大请求的数量最大1000</para>
/// <para>delimiter</para>
/// <returns></returns>
public static List<QiniuFile> FileList(Bucket model)
{
Mac mac = new Mac(AK, SK);
BucketManager bm = new BucketManager(mac); // 返回结果存储在items中
List<QiniuFile> items = new List<QiniuFile>();
// 由于limit限制,可能需要执行多次操作
// 返回值中Marker字段若非空,则表示文件数超过了limit
do
{
var result = bm.ListFiles(model.bucket, model.prefix, model.marker, model.limit, model.delimiter);
//标记
model.marker = result.Result.Marker;
if (result.Result.Items != null)
{
result.Result.Items.ForEach(m =>
{
var date = TimeHelper.GetFullTime(m.PutTime.ToString());
items.Add(new QiniuFile
{
FileName = m.Key.Substring(m.Key.LastIndexOf("/") + ),
Fsize = m.Fsize,
MimeType = m.MimeType,
Src = model.PicDomain + m.Key,
Date = date.ToString("yyyy年MM月dd日"),
Moment = date.ToString("HH:mm tt").Replace("上午", "AM").Replace("下午", "PM")
});
});
}
} while (!string.IsNullOrEmpty(model.marker));
return items;
}

删除图片

 /// <summary>
/// 删除文件
/// </summary>
/// <param name="model"></param>
/// <para>bucket 目标空间 默认:studystone</para>
/// <para>saveFilePath 目标文件,非全路径 例如: temp/logo.png</para>
/// <returns></returns>
public static UploadResult Delete(Bucket model)
{
var result = new UploadResult();
try
{
Mac mac = new Mac(AK, SK);
BucketManager target = new BucketManager(mac);
var data = target.Delete(model.bucket, model.saveFilePath);
switch (data.Code)
{
//上传成功
case :
result.State = UploadState.Success;
break;
case :
result.State = UploadState.TypeNotAllow;
result.ErrorMessage = " 待删除资源不存在";
break;
default:
result.State = UploadState.Unknown;
result.ErrorMessage = "文件删除失败";
break;
}
}
catch (Exception)
{
result.State = UploadState.Unknown;
result.ErrorMessage = "文件删除失败";
}
return result;
}