下面是“C#使用百度Ueditor富文本框实现上传文件”的完整攻略。
准备工作
-
安装百度Ueditor
在NuGet中检索百度ueditor.net.Mvc或者使用百度Ueditor官网提供的下载方式,将ueditor的dll放入Solution下面的bin目录下。 -
配置Ueditor
(1)在网站的Web.config文件中,加入如下内容。
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
<system.WebServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824"/>
</requestFiltering>
</security>
</system.WebServer>
其中,httpRuntime
指定了最大上传文件大小,这里的1048576表示1M;而requestLimits
也指定了最大上传文件大小,这里的1073741824表示1G。
(2)在config.json文件中,配置如下内容。
"imageUrlPrefix": "",
"imagePathFormat": "/Uploads/{yyyy}{mm}{dd}/{time}{rand:6}",
"imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
"fileUrlPrefix": "",
"filePathFormat": "/Uploads/{yyyy}{mm}{dd}/{time}{rand:6}",
"fileAllowFiles": [
".txt", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".rar", ".zip"
],
"catcherLocalDomain": ["127.0.0.1","localhost"],
"catchRemoteImageEnable":false
这里的imageUrlPrefix
和fileUrlPrefix
指定了上传文件的路径前缀;而imagePathFormat
和filePathFormat
则指定了上传文件的具体路径格式;imageAllowFiles
和fileAllowFiles
则指定了允许上传的文件类型。
实现过程
- 控制器
在控制器中,定义上传文件的接口,并接收返回值。
[HttpPost]
public JsonResult UploadFile()
{
var result = new UpLoadFileResult();
try
{
var file = Request.Files[0];
var fileName = Path.Combine(Server.MapPath("~/Uploads"), DateTime.Now.ToString("yyyyMMddhhmmss") + Path.GetExtension(file.FileName));
var savePath = fileName.Replace(Server.MapPath("~"), "");
file.SaveAs(fileName);
result.Url = savePath.Replace(@"\", "/");
result.State = "SUCCESS";
}
catch
{
result.State = "ERROR";
}
return Json(result);
}
/// <summary>
/// 上传文件的返回结果
/// </summary>
public class UpLoadFileResult
{
public string State { get; set; }
public string Url { get; set; }
}
其中,UpLoadFileResult类是用于返回上传文件的状态信息。
- 视图层
在视图层中,使用Ueditor富文本框,并配置文件上传功能。
@using UEditor;
@{
ViewBag.Title = "Index";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - My ASP.NET Application</title>
<script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script src="@Url.Content("~/ueditor/ueditor.config.js")"></script>
<script src="@Url.Content("~/ueditor/ueditor.all.js")"></script>
</head>
<body>
<div>
<textarea id="content" name="content"></textarea>
</div>
</body>
<script>
var editor = new UE.ui.Editor({
initialFrameHeight: 280, //初始化高度
scaleEnabled: false, //禁用缩放
toolbars: [[
'undo',
'redo',
'bold',
'italic',
'underline',
'fontsize',
'forecolor',
'BackGroundColor',
'justifyleft',
'justifycenter',
'justifyright',
'insertunorderedlist',
'insertorderedlist',
'link',
'unlink',
'attachment'
]]
});
editor.render('content');
var attachment = null;
// 上传文件
editor.ready(function () {
editor.addListener("beforeInsertImage", function (t, arg) {
for (var i = 0; i < arg.length; i++) {
if (attachment != null) {
arg[i].url = attachment;
}
}
attachment = null;
});
editor.addListener("afterUpfile", function (t, arg) {
if (arg.state === "SUCCESS") {
attachment = arg.url;
var field = editor.getDialog("attachment");
var dialog = new UE.ui.Dialog({
iframeUrl: "@Url.Action("UploadFile", "Home")",
editor: editor,
name: "attachment",
title: "附件上传",
cssRules: "width:600px;height:400px;"
});
dialog.render();
dialog.open();
}
});
});
</script>
</html>
其中,UEditor的配置信息包括:
- initialFrameHeight:初始化高度,即编辑器的高度;
- scaleEnabled:是否启用缩放功能;
-
toolbars:工具栏,默认启用的工具。
-
示例
(1)将上传的文件保存在本地
[HttpPost]
public JsonResult UploadFile()
{
var result = new UpLoadFileResult();
try
{
var file = Request.Files[0];
var fileName = Path.Combine(Server.MapPath("~/Uploads"), DateTime.Now.ToString("yyyyMMddhhmmss") + Path.GetExtension(file.FileName));
var savePath = fileName.Replace(Server.MapPath("~"), "");
file.SaveAs(fileName);
result.Url = savePath.Replace(@"\", "/");
result.State = "SUCCESS";
}
catch
{
result.State = "ERROR";
}
return Json(result);
}
在Ueditor的配置信息编辑窗口中,可以直接上传文件,并将其保存在本地。
(2)将上传的文件存储在Azure Blob Storage中
[HttpPost]
public JsonResult UploadFile()
{
var result = new UpLoadFileResult();
try
{
var file = Request.Files[0];
var fileName = Path.Combine(Server.MapPath("~/Uploads"), DateTime.Now.ToString("yyyyMMddhhmmss") + Path.GetExtension(file.FileName));
var savePath = fileName.Replace(Server.MapPath("~"), "");
//将文件上传到Azure Blob Storage
var connectionString = ConfigurationManager.ConnectionStrings["AzureCn"].ConnectionString;
var account = CloudStorageAccount.Parse(connectionString);
var blobClient = account.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("ueditor");
container.CreateIfNotExists();
var blobName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
var blob = container.GetBlockBlobReference(blobName);
using (var fileStream = file.InputStream)
{
blob.UploadFromStream(fileStream);
blob.Properties.ContentType = file.ContentType;
blob.SetProperties();
}
result.Url = "https://" + account.BlobEndpoint.Host + "/" + container.Name + "/" + blobName;
result.State = "SUCCESS";
}
catch
{
result.State = "ERROR";
}
return Json(result);
}
在Ueditor的配置信息编辑窗口中,上传的文件会直接存储在Azure Blob Storage中,并返回其路径。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#使用百度Ueditor富文本框实现上传文件 - Python技术站