ASP. NET MVC5 implements file upload and address change processing (5), asp. netmvc5

Source: Internet
Author: User
Tags subdomain name

ASP. NET MVC5 implements file upload and address change processing (5), asp. netmvc5

1. Process uploaded and duplicated files
The principle of file processing is: not to save files in the database, but to save file information (such as Hash values) in the database ). Generally, the problem of File Duplication is sufficient to rename a file using MD5 of a file. If you are obsessive, you can 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;    }


Ii. upload an independent File
Website logos, classification icons, and other scenarios need to be uploaded separately. By using the features of UIHintAttribute or custom inheritance from UIHintAttribute, we can eliminate repeated code of the front-end logic of file upload and use a unified view file for processing. I have used Uplodify and AjaxFileUploader. The former has flash dependency and cookie problems, and the latter is basically outdated. Here we use the File Upload Component in KindEditor for demonstration. The core of the non-Flash IE6 + solution is to implement pseudo AJax upload through iframe, and the core is to post to the server through 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 inherit UIHintAttribute. The path specifies the lower-level Address of the storage, such as DropDownAttribute and EditorAtrribute. 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 to Shared and create the 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>

3. upload files in the editor
The main difference between file upload and individual file upload in the editor is the processing of the returned values after the upload. The editor needs to insert the url to the editing location. The editor has used CKeditor and UMeditor. You need to modify the source code to solve the path problem. If the configuration of the upload address and return value cannot be easily adjusted in the view, I personally do not think it is a good editor. This is like a class library that cannot be expanded or customized. KindEditor is still used for demonstration. 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',      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>

4. process the image path in the article
It seems that this problem can be avoided, but it is actually unavoidable. Change the directory, domain name, and port, and use the subdomain name or other domain name as the image server. In this case, we must handle this problem. Otherwise, we will waste more time in the future. This is not a small problem. Open the editor of each website that supports inserting images and view the path of a piece, which is mostly an absolute url or based only on the root directory. If you provide the product to the customer, it is even more difficult for the customer to replace the path in the article.

1. Do not store the file path in the database. Use the URL path as the storage.

2. Use the html base element to reference relative paths.

It is the base element. Some people may think this base is dispensable, but there is no more concise and elegant solution than the base in terms of image path processing. At least I have not found it. In fact, all static resources can be removed to external storage, if you need. During the test, we switched back to using local storage.

@{  var baseUrl = UploadManager.UrlPrefix;}<!DOCTYPE html>

5. Handle upload address changes
When we need an independent image server to process uploads or use a third-party image storage service, our upload address is changed. If the image path we just mentioned is the same, therefore, the upload path and image path are configured to facilitate changes. We have switched to youpai cloud and switched to our own server. In actual use, cache is used for configuration in data. To facilitate demonstration, we use the configuration file directly.

First, define the configuration file Handler

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


Configure in web. config

 <configSections>  <section name="UploadConfig" type="SimpleFileManager.UploadConfig, SimpleFileManager" requirePermission="false" /> </configSections> <UploadConfig>  <UploadUrl href="~/File/Upload/" />  <UrlPrefix href="~/Upload/" /> </UploadConfig>

Use UploadMange to cache and manage 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;      }    }  }

The specific technical dependencies such as Md5 of file Hash, Json processing of returned values, generation of complete URLs, and file storage are stored in UploadHelper for ease of demonstration, because these are not the focus. In actual applications, interfaces can be isolated and decoupled through IoC injection.

The above is the whole process of how ASP. NET MVC5 implements file upload and address change processing. I hope this will be helpful for your learning.

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.