asp.net MVC5 implementation of File upload and Address change processing (5) _ Practical Skills

Source: Internet
Author: User
Tags form post html form html form post md5 static class

I. Uploading files and duplicate file processing
the principle of file processing is not to save the file in the database, only to save the file information (hash value, etc.) in the database. Take the file MD5 rename file in general enough to deal with the duplication of files, obsessive tendencies may consider combining MD5 with 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. separate file upload
Site logo, category icons and other scenarios require a separate file upload processing. By using Uihintattribute or custom inherited Uihintattribute features, we eliminate the repetitive code from the front-end logic of file uploads and use a unified view file for processing. Once used uplodify and Ajaxfileuploader, the former has a flash dependency and cookie problem, the latter is basically obsolete. Here we use the File Upload component in Kindeditor as a demo. Non-flash support ie6+ The core of the solution is to achieve pseudo Ajax upload through the IFRAME, the core or through the HTML form post to the server.

  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 the path path specifies the subordinate address of the store, 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 EditorTemplates folder in shared, create new upload.cshtml file.

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

three. File uploads in the editor the main difference between file uploads in the
Editor and individual file uploads is that the return value is processed after uploading, and the editor needs to insert the URL into the edit location. The editor uses CKEditor and Umeditor, both of which require me to change the source code to handle the path problem. Upload address and return the value of the configuration if it is not convenient to adjust the editor in the view, I personally do not think is a good editor, this is like a class library can not expand and custom configuration. Still using Kindeditor as a demo. The editor.cshtml

 <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 ', Formatuplo Adurl:false, Allowfilemanager:false @if (usesimple) {<text>, items: [' Fontn Ame ', ' fontsize ', ' | ', ' forecolor ', ' hilitecolor ', ' bold ', ' italic ', ' underline ', ' removeformat ', ' | ', ' justif Yleft ', ' justifycenter ', ' justifyright ', ' insertorderedlist ', ' insertunorderedlist ', ' | ', ' emoticons ', ' image '
  , ' link '] </text>}};
}); </script> 

Four. Process the image path in the article
The play is coming, this seemingly problem can be avoided, in fact, really can not avoid. Replacing directories, domain names and ports, using subdomains or other domain names as picture servers, and so on, we have to deal with this problem, or we will waste more time in the future. This is not a minor problem, open the editor for each Web site that supports inserting a picture, and look at the path to the picture, most of it is an absolute URL, or it is based only on the root directory. If you are offering to a customer in the form of a product, it is not even possible 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 store.

2. Use HTML base element to resolve relative path reference problem.

is the base element, some people may think this base is dispensable, but there is no simpler and more elegant solution to the problem of dealing with the image path than base. At least I've never found it. You can actually remove all the static resources to the external store, if you need to. At the time of testing, we switched back to using local storage.

@{
  var baseurl = uploadmanager.urlprefix;
}
<! DOCTYPE html>
 
 

Five. Handle the change of the uploaded address
We need a standalone image server to handle uploading or using a third party image storage service when our upload address has changed, if just mentioned the image path, so we will upload path and image path are configured to facilitate changes, we have switched to the cloud and switch to its own server. I use caching when I'm actually using it when I'm using it in my data. To make it easier to demonstrate we use the configuration file directly.

First define the handler for the configuration file

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


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

Md5 of file hashes, JSON processing of return values, generation of complete URLs, and preservation of files The dependencies of these specific technologies are placed in the Uploadhelper for demonstration purposes, as these are not the focus. In practical applications, interface isolation can be taken and decoupled through IOC injection.

The above is ASP.net MVC5 how to achieve file upload and address change processing all the process, I hope to help you learn.

Related Article

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.