ASP. NET MVC file upload and path processing

Source: Internet
Author: User

ASP. NET MVC file upload and path processing summary

Directory

The file upload and path processing must address the actual issues listed below:

1. Duplicate file processing

2. Individual file Upload

3. File Upload in Editor

4. Working with picture paths in an article

5. Handling changes to the upload address

I. uploading files and repeating file processing

The principle of file processing is: Do not save the file in the database, only save the file information (hash value, etc.) in the database. Take the file of the MD5 rename file in general enough to deal with the duplication of files, obsessive compulsive disorder may consider combining MD5 and other digest algorithms.

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;        }

Two. individual file upload

Website logo, category icon and other scenarios require the processing of separate file upload. By using Uihintattribute or customizing attributes that inherit from Uihintattribute, we eliminate duplicate code for the front-end logic of file uploads, using a unified view file processing. Uplodify and Ajaxfileuploader have been used, and the former has flash dependencies and cookie problems, which are largely obsolete. Here we use the File Upload component in Kindeditor as a demonstration. The core of the non-Flash support ie6+ scheme is to implement pseudo-Ajax uploads via IFRAME, and the core is to post to the server via HTML form.

    public class Uploadmodel    {        [Display (Name = "icon]]        [UIHint (" Upload ")] public        string Image {get; set;}        [Display (Name = "simple Mode")]        [UIHint ("editor")]        [Additionalmetadata ("Usesimple", true)]        public string Text1 {get; set;}        [Display (Name = "Standard mode")]        [UIHint ("editor")]        public string Text2 {get; set;}    }

In our actual project we take the way of inheriting Uihintattribute, where path paths specify the subordinate addresses of the stores, similar to Dropdownattribute, Editoratrribute, and so on. For reference only.

    [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: Add the EditorTemplates folder in shared and create a new upload.cshtml file.

<script>    kindeditor.ready (function (K) {        var editor = k.editor ({            allowfilemanager:false,            Allowimageupload:true,            Formatuploadurl:false,            uploadjson: ' @url ',        });        K (' #[email protected] '). Click (function () {            editor.loadplugin (' InsertFile ', function () {                Editor.plugin.fileDialog ({                    fileurl:k (' # @id '). Val (),                    clickfn:function (URL, title) {                        K (' # @id '). Val ( URL);                        $ (' #[email protected] '). attr (' src ', url);                        Editor.hidedialog (    )    ;});}); $ (' #[email protected] '). Click (function () {        $ (' # @id '). attr (' value ', ');        $ (' #[email protected] '). attr (' src ', ' @Url. Content ("~/images/default.png");    }); </script>

Three. Uploading files in the editor

The main difference between file uploads and individual file uploads in the editor is the processing of the return value after uploading, where the editor needs to insert the URL into the edit location. The editor has used CKEditor and Umeditor, both of which require me to change the source code to handle the path problem. The configuration of the upload address and return value if it is not convenient to adjust the editor in the view, I personally do not think that is a good editor, which is like a class library can not be extended and custom configuration. Kindeditor is still used as a demonstration. The main contents of editor.cshtml are as follows:

123456789101112131415161718192021 <scripttype="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>

Four. Working with picture paths in an article

The play came, this seemingly problem can be avoided, in fact, really can not avoid. Changing directories, domain names and ports, using subdomains or other domain names as image servers, and so on, have made it a problem that we have to deal with, or we'll waste more time in the future. This is not a small problem, open the support to insert the image of the individual Web site editor, view a path, mostly absolute URL, or only based on the root directory. If you provide the customer in the form of a product, it is more impossible to ask the customer to replace the path in the article.

1. The file path is not stored in the database, and the URL path is used as the storage.

2. Use the HTML base element to resolve reference problems with relative paths.

is the base element, perhaps some people think this base is dispensable, but in the process of dealing with the picture path, there is no more concise and elegant solution than base. At least I haven't found it. You can actually remove all the static resources to the external storage, if you need to. When testing, we switch back to using local storage.

@{    var baseUrl = Uploadmanager.urlprefix;} <! DOCTYPE html>

Five. Handling changes to the upload address

We need independent image server processing upload or use of third-party image storage services, our upload address has changed, if just mentioned the image path, so we will upload the path and image path are configured to make changes to the way to facilitate change, we have switched to the cloud and switch to the own server. The cache is used when the configuration is used in the data when I am actually using it. For illustrative purposes, we use the configuration file directly.

First define a handler for the configuration file

    public class Uploadconfig:iconfigurationsectionhandler {public Object Create (object parent, Object Config            Context, 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;}} 

configuring in Web. config

<configSections>    <section name= "Uploadconfig" type= "Simplefilemanager.uploadconfig, Simplefilemanager "requirepermission=" false "/>  </configSections>  <UploadConfig>    < Uploadurl href= "~/file/upload/"/>    <urlprefix href= "~/upload/"/> </UploadConfig>

Using Uploadmange caching and managing configurations

 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; }        }    }

ASP. NET MVC file upload and path processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.