ASP.NET MVC 文件上传和路径处理

摘要:
ASP。NET MVC文件的上传和路径处理摘要目录文件的上传与路径处理必须解决以下实际问题:1。重复文件处理2。单个文件上传3。在编辑器中上传文件4。处理文章5中的图像路径。处理上传地址1的更改。上传文件和重复文件处理文件处理的原则是:不将文件保存在数据库中,只将文件信息保存在数据库。通过使用UIHintAttribute或自定义从UIHintAattribute继承的功能,我们消除了文件上传前端逻辑的重复代码,并使用统一的视图文件进行处理。这里我们使用KindEditor中的文件上传组件作为演示。
ASP.NET MVC 文件上传和路径处理总结

目录

 

文件的上传和路径处理必须解决下面列出的实际问题:

 

1.重复文件处理

 

2.单独文件上传

 

3.编辑器中文件上传

 

4.处理文章中的图片路径

 

5.处理上传地址的变化

 

一.上传文件和重复文件处理

 

文件处理的原则是:不在数据库中保存文件,只在数据库中保存文件信息(Hash值等)。采取文件的MD5重命名文件在一般情况足够处理文件的重复问题,强迫症倾向则可以考虑将MD5和其他摘要算法结合。

 
复制代码
     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;
        }
复制代码
 

二.单独文件上传

 

网站Logo、分类图标等各种场景需要单独文件上传的处理。通过使用UIHintAttribute或自定义继承自UIHintAttribute的特性我们将文件上传的前端逻辑的重复代码消灭,使用统一的视图文件处理。曾经使用过Uplodify和AjaxFileUploader,前者存在flash依赖和cookie问题,后者基本已经过时。此处我们采用KindEditor中的文件上传组件作为演示。非Flash的支持IE6+的方案的核心都是通过iframe方式实现伪AJax上传,核心还是通过html form post到服务器。

 
复制代码
    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; }
    }
复制代码
 

在我们的实际项目中采取继承UIHintAttribute的方式,其中的path路径指定存储的下级地址,类似的还有DropDownAttribute、EditorAtrribute等等。仅供参考。

 
复制代码
    [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>
复制代码
   

三.编辑器中的文件上传

 

编辑器中的文件上传和单独文件上传的主要区别是上传后返回值的处理,编辑器需要将url插入到编辑的位置。编辑器采用过CKeditor和UMeditor,两者都需要我改源代码才能处理路径问题。上传地址和返回值的配置如果不能方便的视图中调整的编辑器,我个人不认为是好编辑器,这就好比一个类库没法扩展和自定义配置一样。仍然采用KindEditor作为演示。Editor.cshtml的主要内容如下:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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>
 

四.处理文章中的图片路径

 

重头戏来了,这个看似问题可以回避,其实真的无法回避。更换目录、域名和端口,使用子域名或其他域名作为图片服务器等等,这些情况让我们必须处理好这个问题,否则日后会浪费更多的时间。这不是小问题,打开支持插入图片的各个网站的编辑器,查看一下图片的路径,大多是绝对url的,又或者只基于根目录的。如果你以产品的形式提供给客户,更不可能要求客户自己挨个替换文章中的路径了。

 

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="http://t.zoukankan.com/~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

    <title>@ViewBag.Title</title>
    <base href="http://t.zoukankan.com/@baseUrl" />
    
    <script src="http://t.zoukankan.com/~/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; }
    }
复制代码
 

在web.config中配置

 
复制代码
 <configSections>
    <section name="UploadConfig" type="SimpleFileManager.UploadConfig, SimpleFileManager" requirePermission="false" />
  </configSections>
  <UploadConfig>
    <UploadUrl href="http://t.zoukankan.com/~/File/Upload/" />
    <UrlPrefix href="http://t.zoukankan.com/~/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 MVC 文件上传和路径处理第17张

 

Demo下载:点击下载

   
如果这篇博客内容对您稍有帮助或略有借鉴,请您推荐它帮助更多的人。
 
 
 
分类: ASP.NET

免责声明:文章转载自《ASP.NET MVC 文件上传和路径处理》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇springboot配置rabbitmq的序列化反序列化格式spring boot jar 进程自动停止,自动终止,不能后台持续运行下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Js 之移动端富文本插件(wangEditor)

文档:https://www.kancloud.cn/wangfupeng/wangeditor3/332599 下载:https://github.com/wangfupeng1988/wangEditor/releases 一、效果图  二、代码示例 <div id="editorContainer" style="margin-bottom...

Linux 配置gitee

安装好git后, 如何配置连接至gitee ?首先, 需要在官网注册一个gitee账号, 然后进行以下配置步骤: 1. 设置账号 $ git config --global user.name "your name" 2. 设置邮箱 $ git config --global user.email "your email" 3. 生成密钥 $ ssh-...

Vue中发送ajax请求——axios使用详解

Vue中发送ajax请求——axios使用详解目录axios 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用功能特性 在浏览器中发送 XMLHttpRequests 请求 在 node.js 中发送 http请求 支持 Promise API 拦截请求和响应 转换请求和响应数据 自动转换 JSON 数据 客户端支持...

laravel 踩坑 env,config

正常情况: env 方法 可以获取 .env 文件的值 config 可以获取 config 文件夹下 指定配置的值 非正常情况: 当我们执行了 php artisan config:cache 之后 在bootstrap/cache 文件夹下 会生成一个 config.php 文件 这个文件包含了 config 文件夹下的所有文件内容,并以文件...

上传大文件的解决方案

需求: 项目要支持大文件上传功能,经过讨论,初步将文件上传大小控制在20G内,因此自己需要在项目中进行文件上传部分的调整和配置,自己将大小都以20G来进行限制。 PC端全平台支持,要求支持Windows,Mac,Linux 支持所有浏览器。 支持文件批量上传 支持文件夹上传,且要求在服务端保留层级结构。文件夹数量要求支持到10W。 支持大文件断点续传,要求...

Hi3518EV300编译U-Boot和内核报错:loadlocale.c:130: _nl_intern_locale_data: Assertion `cnt &amp;lt; (sizeof (_nl_value_type_LC_TIME) / sizeof (_nl_value_type_LC_TIME[0]))' failed. Aborted (core dumped)

下载Hi3518EV300的SDK后编译内核和U-boot,发现爆出如下错误: scripts/kconfig/conf --silentoldconfig Kconfig Aborted (core dumped) Aborted (core dumped) Aborted (core dumped) Aborted (core dumped) Abo...