UEditor上傳圖片到七牛雲儲存(c#)


我們的網站一般放在虛擬空間或者服務器上,圖片如果存在本地目錄,會占用很多空間和流量,還增加了負擔,好的辦法是把圖片存放到雲儲存服務里面,平時用url去拿

雲儲存:普遍說又拍雲和七牛比較好,看到七牛免費額度很大,網上評價也挺好的,我就選了七牛

編輯器:我用的是百度的UEditor編輯器,之后需要修改一些的開放的類和js文件

下面寫一下c#版本的修改方法(java版本在下一篇

 

一、集成UEditor

1、在項目中加入UEditor

在UEditor的下載頁,可以下載到最新的1.4.3.3 .Net版本(UTF-8)

把解壓出的文件夾放進項目

2、添加Newtonsoft.Json.dll引用

項目 -> 引用 -> 添加引用 -> 瀏覽(最近),找到UEditor\net\Bin\Newtonsoft.Json.dll添加引用

3、將UEditor嵌入頁面

新建一個頁面,內容是:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UEditorPage.aspx.cs" Inherits="NetImgUpload.UEditorPage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>UEditor上傳圖片到七牛(.net)</title>
    <script src="/UEditor/ueditor.config.js" type="text/javascript"></script>
    <script src="/UEditor/ueditor.all.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
        <script type="text/plain" id="editor" name="editContent" style="width:600px; height:300px;"></script>
        <script type="text/javascript">
            var ue = UE.getEditor('editor');
        </script>
    </form>
</body>
</html>

4、運行效果

最后的文件目錄:

頁面的運行效果:

 

二、集成七牛sdk

1、下載七牛sdk

在七牛sdk的下載頁,找到c#(服務端)點擊安裝,下載最新的v6.1.5版本

把解壓出的文件夾放在項目同一目錄

(sdk是為了方便我們開發而寫的一個工具包,七牛賬戶的申請、添加對象儲存都非常簡單,這里就不說了)

2、引入七牛sdk

解決方案 -> 添加 -> 現有項目,找到QiniuSDK\Qiniu\Qiniu.4.0.csproj添加現有項目

項目 -> 引用 -> 項目(解決方案),勾選Qiniu.4.0添加引用

3、修改Newtonsoft.Json.dll引用

七牛sdk里面默認引用了.net 2.0的Newtonsoft.Json.dll,和之前UEditor里引用的.net 4.0版不一樣,需要改成一樣的,不然之后圖片上傳會失敗

刪除七牛sdk項目引用里的Newtonsoft.Json.dll,然后添加引用UEditor里的Newtonsoft.Json.dll,步驟和上面一樣

最后的文件目錄:

 

三、上傳圖片到七牛

1、添加QiniuHelper.cs幫助類

這是為了接下來方便修改寫的一個工具類,使用它可以省一些重復代碼

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using Qiniu.IO;
using Qiniu.RS;

namespace NetImgUpload
{
    /// <summary>
    /// 七牛工具類
    /// </summary>
    public class QiniuHelper
    {
        /// <summary>
        /// 空間名
        /// </summary>
        private static readonly string Scope = ConfigurationManager.AppSettings["QiniuScope"];

        /// <summary>
        /// 域名
        /// </summary>
        private static readonly string Url = ConfigurationManager.AppSettings["QiniuUrl"];

        /// <summary>
        /// 插入數據並返回交互結果
        /// </summary>
        /// <param name="imageFile"></param>
        /// <returns></returns>
        public static PutRet GetResult(byte[] imageFile)
        {
            var target = new IOClient();
            var extra = new PutExtra
            {
                MimeType = "text/plain",
                Crc32 = 123,
                CheckCrc = CheckCrcType.CHECK,
                Params = new Dictionary<string, string>()
            };
            var put = new PutPolicy(Scope);
            return target.Put(put.Token(), Guid.NewGuid().ToString(), new MemoryStream(imageFile), extra);
        }

        /// <summary>
        /// 獲得url地址
        /// </summary>
        /// <returns></returns>
        public static string GetUrl(string key)
        {
            return GetPolicy.MakeBaseUrl(Url, key);
        }

        /// <summary>
        /// 刪除數據
        /// </summary>
        /// <param name="key"></param>
        public static void DeleteData(string key)
        {
            var client = new RSClient();
            client.Delete(new EntryPath(Scope, key));
        }

        /// <summary>
        /// 批量刪除數據
        /// </summary>
        /// <param name="keys"></param>
        public static void DeleteDatas(string keys)
        {
            var client = new RSClient();
            var entryPaths = new List<EntryPath>();
            foreach (string key in keys.Split(','))
            {
                entryPaths.Add(new EntryPath(Scope, key.Replace("'", "")));
            }
            client.BatchDelete(entryPaths.ToArray());
        }
    }
}

 

2、修改UploadHandler.cs類

找到UEditor\net\App_Code\UploadHandler.cs類,找到以下代碼:

if (!Directory.Exists(Path.GetDirectoryName(localPath)))
{
    Directory.CreateDirectory(Path.GetDirectoryName(localPath));
}
File.WriteAllBytes(localPath, uploadFileBytes);
Result.Url = savePath;
Result.State = UploadState.Success;

修改成:

#region 不再需要儲存文件到服務器

//if (!Directory.Exists(Path.GetDirectoryName(localPath)))
//{
//    Directory.CreateDirectory(Path.GetDirectoryName(localPath));
//}
//File.WriteAllBytes(localPath, uploadFileBytes);
//Result.Url = savePath;
//Result.State = UploadState.Success;

#endregion

#region 上傳文件到七牛

var ret = QiniuHelper.GetResult(uploadFileBytes);

if (ret.OK)
{
    Result.Url = QiniuHelper.GetUrl(ret.key);
    Result.State = UploadState.Success;
}

#endregion

這樣原來圖片上傳到本地的方式就改成上傳到七牛了

 

3、修改七牛sdk的Config.cs

找到QiniuSDK\Qiniu\Conf\Config.cs類,找到以下代碼:

#region 帳戶信息
/// <summary>
/// 七牛提供的公鑰,用於識別用戶
/// </summary>
public static string ACCESS_KEY = "<Please apply your access key>";
/// <summary>
/// 七牛提供的秘鑰,不要在客戶端初始化該變量
/// </summary>
public static string SECRET_KEY = "<Dont send your secret key to anyone>";
#endregion

修改成:

#region 帳戶信息
/// <summary>
/// 七牛提供的公鑰,用於識別用戶
/// </summary>
public static string ACCESS_KEY = ConfigurationManager.AppSettings["QiniuAccessKey"];
/// <summary>
/// 七牛提供的秘鑰,不要在客戶端初始化該變量
/// </summary>
public static string SECRET_KEY = ConfigurationManager.AppSettings["QiniuSecretKey"];
#endregion

 

4、修改網站的web.config

在configuration節點的appSettings節點下增加:

<!--七牛的相關配置-->
<add key="QiniuScope" value="xxxx" />
<add key="QiniuUrl" value="xxxxxxxxx.bkt.clouddn.com" />
<add key="QiniuAccessKey" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
<add key="QiniuSecretKey" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />

QiniuScope是存儲空間的名稱

QiniuUrl是存儲空間的域名(也可以用自己的正式域名)

QiniuAccessKey和QiniuSecretKey是用戶的一對密鑰,在個人面板 -> 個人中心 -> 密鑰管理 界面中可以創建、查看

 

5、修改UEditor的配置

(1)、修改config.json

找到UEditor\net\config.json文件,修改imageUrlPrefix(圖片訪問路徑前綴)為空(因為上傳到七牛了,url是一個完整的路徑,不需要前綴)

(2)、關閉自動本地保存

找到UEditor\ueditor.all.js文件,查找"'contentchange': function () {",在這個函數內增加代碼:

'contentchange': function () {

    //關閉自動本地保存
    if (!me.getOpt('enableAutoSave')) {
        return;
    }

這樣就不會經常跳出煩人的提示框了

 

6、圖片上傳運行效果

最后測試一下圖片上傳是否成功

單圖片上傳:

內容里src已經變成了七牛的地址了

再看多圖片上傳:

 

7、demo下載

最新的代碼地址:https://github.com/ctxsdhy/cnblogs-example

 

四、其他擴展

這是我的博客里面使用的,設置所有圖片尺寸和加入相冊功能,其實就是在UEditor里修改幾處js,然后增加一個加入相冊服務

方法暫時不整理了,博客的代碼在這里:https://github.com/ctxsdhy/xsblog

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM