ASP.NET MVC5实现文件上传与地址变化处理(5) |
|
一.上传文件和重复文件处理
public static string Save(HttpPostedFileBase file, string path)
{
var root = "'/Upload/" + path + "/";
var phicyPath = HostingEnvironment.MapPath(root);
Directory.CreateDirectory(phicyPath);
var fileName = Md5(file.InputStream) + file.FileName.Substring(file.FileName.LastIndexOf(.));
file.SaveAs(phicyPath + fileName);
return fileName;
}
public class UploadModel
{
[Display(Name = "图标")]
[UIHint("Upload")]
public string Image { get; set; }
[Display(Name = "简单模式")]
[UIHint("Editor")]
[AdditionalMetadata("useSimple", true)]
public string Text1 { get; set; }
[Display(Name = "标准模式")]
[UIHint("Editor")]
public string Text2 { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
public class UploadAttribute : UIHintAttribute, IMetadataAware
{
public string Path { get; private set; }
public UploadAttribute(string path = "")
: base("Upload")
{
this.Path = path;
}
public virtual void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues.Add("Path", this.Path);
}
}
Razor:在Shared中添加EditorTemplates文件夹,新建Upload.cshtml文件 。
<script>
KindEditor.ready(function (K) {
var editor = K.editor({
allowFileManager: false,
allowImageUpload: true,
formatUploadUrl: false,
uploadJson: @url,
});
K(#btn_@id).click(function () {
editor.loadPlugin(insertfile, function () {
editor.plugin.fileDialog({
fileUrl: K(#@id).val(),
clickFn: function (url, title) {
K(#@id).val(url);
$(#image_@id).attr(src, url);
editor.hideDialog();
}
});
});
});
});
$(#rest_@id).click(function () {
$(#@id).attr(value, );
$(#image_@id).attr(src, @Url.Content("'/Images/default.png"));
});
</script>
三.编辑器中的文件上传
<script type="text/javascript">
var editor;
KindEditor.ready(function (K) {
editor = K.create(textarea[name="@Html.IdForModel()"], {
resizeType: 1,
allowPreviewEmoticons: false,
allowImageUpload: true,
uploadJson: @UploadManager.UploadUrl,
formatUploadUrl: false,
allowFileManager: false
@if(useSimple)
{
<text>, items: [
fontname, fontsize, |, forecolor, hilitecolor, bold, italic, underline,
removeformat, |, justifyleft, justifycenter, justifyright, insertorderedlist,
insertunorderedlist, |, emoticons, image, link]
</text>
}
});
});
</script>
四.处理文章中的图片路径 1.在数据库中不存储文件路径,使用URL路径作为存储 。 2.使用html base元素解决相对路径的引用问题 。 就是base元素,可能有的人认为这个base可有可无,但在处理图片路径的问题上,没有比base更简洁更优雅的方案了 。至少我没有也没找到过 。其实可以把全部的静态资源都移除到外部存储,如果你需要 。在测试时,我们切换回使用本地存储 。
@{
var baseUrl = UploadManager.UrlPrefix;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="'/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<title>@ViewBag.Title</title>
<base href="@baseUrl" />
<script src="'/Scripts/jquery-1.11.2.min.js"></script>
@RenderSection("head",false)
</head>
<body>
@RenderBody()
</body>
</html>
五.处理上传地址的变化 首先定义配置文件的处理程序
public class UploadConfig : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
var config = new UploadConfig();
var urloadUrlNode = section.SelectSingleNode("UploadUrl");
if (urloadUrlNode != null && urloadUrlNode.Attributes != null && urloadUrlNode.Attributes["href"] != null)
{
config.UploadUrl = Convert.ToString(urloadUrlNode.Attributes["href"].Value);
}
var urlPrefixNode = section.SelectSingleNode("UrlPrefix");
if (urlPrefixNode != null && urlPrefixNode.Attributes != null && urlPrefixNode.Attributes["href"] != null)
{
config.UrlPrefix = Convert.ToString(urlPrefixNode.Attributes["href"].Value);
}
return config;
}
public string UploadUrl { get; private set; }
public string UrlPrefix { get; private set; }
}
<configSections> <section name="UploadConfig" type="SimpleFileManager.UploadConfig, SimpleFileManager" requirePermission="false" /> </configSections> <UploadConfig> <UploadUrl href="'/File/Upload/" /> <UrlPrefix href="'/Upload/" /> </UploadConfig> 使用UploadMange缓存和管理配置
public static class UploadManager
{
private static string uploadUrl;
private static string urlPrefix;
static UploadManager()
{
var config = ConfigurationManager.GetSection("UploadConfig") as UploadConfig;
var url = config != null && !string.IsNullOrEmpty(config.UploadUrl) ? config.UploadUrl : "'/File/Upload";
uploadUrl = url.StartsWith("'") ? UploadHelper.GetUrlFromVisualPath(url) : url;
var prefix = config != null && !string.IsNullOrEmpty(config.UrlPrefix) ? config.UrlPrefix : "'/Upload";
urlPrefix = prefix.StartsWith("'") ? UploadHelper.GetUrlFromVisualPath(prefix) : prefix;
}
public static string UploadUrl
{
get
{
return uploadUrl;
}
}
public static string UrlPrefix
{
get
{
return urlPrefix;
}
}
}
文件Hash的Md5、返回值的Json处理、完整URL的生成和文件的保存这些具体技术的依赖为了便于演示,统一放置在UploadHelper中,因为这些不是重点 。实际应用中可以采取接口隔离并通过IoC注入的方式解耦 。
以上就是ASP.NET MVC5如何实现文件上传与地址变化处理的全部过程,希望对大家的学习有所帮助 。 |