We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

I want to designate the path saved when I insert the image in Rich Text Editor as the path to the network server.

Hi.

specified the storage path of the image inserted in the rich text editor as the path to another server connected to the network.

The image was saved to the desired server path using the 'saveUrl' option on the <e-rich text editor-insert image settings> tag, but the saved path is not accessible when loading the image into cshtml.

I wonder how to set the 'path' option used to load images to achieve the desired results.


----------------------------------------------------------  Source  -------------------------------------------------------------

<WriteBoard.cshtml>

@{
    ViewData["Title"] = "Write Board";


    var userEmail = Context.User.Claims.ToList()[1].Value;
}


<div class="row">
    <div class="col-xl-12">
        <hr style="border: solid 1px;" />
        <h4 style="margin-left:20px;">@ViewBag.path</h4>
        <hr style="border: solid 1px;" />
    </div>
</div>
<div class="row">
    <div class="col-xl-12">
        <ejs-textbox id="title" cssClass="e-input" placeholder="Please enter a title." floatLabelType="Auto" created="viewLoad"></ejs-textbox>
    </div>
</div>
<div class="row" style="margin-top: 10px; margin-bottom: 10px;">
    <div class="col-xl-12">
        <input type='file' id="UploadFiles" name="UploadFiles" />
    </div>
</div>
<div class="row">
    <div class="col-xl-12">
        <ejs-richtexteditor id="RichContentBox" name="content" height=400 actionComplete="actionComplate">
            <e-richtexteditor-insertimagesettings saveUrl="/Board/SaveImage" removeUrl="/Board/RemoveImage" path="\\66.10.53.40\cap\BoardImage\"></e-richtexteditor-insertimagesettings>
            <e-content-template></e-content-template>
        </ejs-richtexteditor>
    </div>
</div>
<div class="row" style="margin-top:10px;">
    <div class="col-xl-12 text-right">
        <button class="e-btn" onclick="BoardSaveBtnClick()" style="font-size:12px; height:30px; width: 70px;">Save</button>
    </div>
</div>


<script>
    function viewLoad(args) {
        var Uploader = new ej.inputs.Uploader({
            asyncSettings: {
                saveUrl: "/Board/Upload?mcode=" + sessionStorage.getItem('MenuId'),
                removeUrl: "/Board/Remove?sMenuCode=" + sessionStorage.getItem('MenuId'),
            },
            autoUpload: true,
            multiple: true
        });


        var MenuCode = sessionStorage.getItem('MenuId');


        //'핵심기술 100선' 메뉴에서만 업로드 파일 형식 제한(PDF만 가능)
        if (MenuCode == "130700") {
            Uploader.allowedExtensions = ".pdf";
        }


        Uploader.appendTo('#UploadFiles');
    }


    function onBeforeUpload(args) {
        alert("File MIME type is: " + args.fileData.rawFile.type);
    }


    function BoardSaveBtnClick() {
        var TitleBox = document.getElementById('title').ej2_instances[0];
        var ContentBox = document.getElementById('RichContentBox').ej2_instances[0];
        var FileUploader = document.getElementById('UploadFiles').ej2_instances[0];


        var MenuCode = sessionStorage.getItem('MenuId');
        var Title = TitleBox.inputPreviousValue;
        var Content = ContentBox.cloneValue;
        var UseFile = "N";
        var UploadFile;


        if (FileUploader.filesData.length > 0) {
            UseFile = "Y";
            UploadFile = FileUploader.filesData;
        }


        var data = { MenuCode: MenuCode, Title: Title, Content: Content, UseFile: UseFile, UploadFile: UploadFile };


        $.ajax({
            url: '@Url.Action("WriteBoardSave", "Board")',
            traditional: true,
            data: JSON.stringify(data),
            type: "POST",
            dataType: 'JSON',
            contentType: "application/json",
            success: function (result) {
                if (result == null) {
                    window.location = "/Board/Main?M_CODE=" + MenuCode;
                }
                else {
                    alert(result);
                }
            }
        });
    }
</script>


<BoardController.cs>

using BoardController.Models.Board;
using CAP.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Claims;


namespace CAP.Controllers
{
    [Authorize]
    public class BoardController : Controller
    {
        public static List<string> BoardNoList = new List<string>();


        #region Main [HttpGet]
        [HttpGet]
        public ActionResult Main(int M_CODE)
        {
            ViewBag.mcode = M_CODE;


            MenuModel menuModel = new MenuModel();
            List<MenuModel> list = MenuModel.DQL(menuModel, "S1");


            foreach (MenuModel item in list)
            {
                if (M_CODE == item.M_CODE)
                {
                    ViewBag.path = item.TITLE;
                    break;
                }
            }


            BoardModel boardModel = new BoardModel { P_TYPE = "CAP", M_CODE = M_CODE };
            List<BoardModel> boardList = BoardModel.DQL(boardModel, "S0");


            int i = 1;
            //View에 보여지는 Board No. setting
            foreach (BoardModel model in boardList)
            {
                model.VIEW_NO = i;
                i++;
            }


            ViewBag.dataSource = boardList;


            return View();
        }
        #endregion




        #region Main [HttpPost]
        [HttpPost]
        public ActionResult WriteBoardSave([FromBody]JObject data)
        {
            bool isState = true;


            string sMenuCode = data.SelectToken("MenuCode").ToString();
            string sTitle = data.SelectToken("Title").ToString();
            string sContent = data.SelectToken("Content").ToString();
            string sUseFile = data.SelectToken("UseFile").ToString();
            string sUserEmail = HttpContext.User.FindFirstValue("Email");


            BoardModel NewData = new BoardModel
            {
                P_TYPE = "CAP",
                M_CODE = int.Parse(sMenuCode),
                B_TITLE = sTitle,
                B_CONTENT = sContent,
                USE_FILE = sUseFile,
                EMAIL = sUserEmail
            };


            isState = BoardModel.DML(NewData, "I");


            if (!isState) return Json("A problem occurred during processing. Please try again.");


            if (sUseFile == "Y")
            {
                BoardModel model = new BoardModel { P_TYPE = "CAP", M_CODE = int.Parse(sMenuCode) };
                List<BoardModel> boardList = BoardModel.DQL(model, "S0");
                int iBoardNo = boardList[0].B_NO;


                JToken fileToken = data.SelectToken("UploadFile");


                List<BoardFileModel> fileList = BoardFileModel.JObjectToModelList(fileToken);


                foreach (BoardFileModel file in fileList)
                {
                    file.B_NO = iBoardNo;
                    file.FILE_PATH = FilePath.BasePath + $@"\board\{sMenuCode}" + $@"\{file.FILE_NM}.{file.FILE_EXTSN}";
                    isState = BoardFileModel.DML(file, "I");


                    if (!isState) Json("A problem occurred while uploading the files. Please try again.");
                }
            }


            return Json(null);
        }
        #endregion




        #region WriteBoard
        public IActionResult WriteBoard(string sMenuCode)
        {
            MenuModel model = new MenuModel { M_CODE = int.Parse(sMenuCode) };
            List<MenuModel> list = MenuModel.DQL(model, "S5");


            ViewBag.path = list[0].TITLE;


            ViewBag.ImagePath = FilePath.BasePath;


            return View();
        }
        #endregion




        #region EditBoard
        public ActionResult EditBoard(string sBoardNo, string sMenuCode)
        {
            MenuModel menuModel = new MenuModel { M_CODE = int.Parse(sMenuCode) };
            List<MenuModel> menu = MenuModel.DQL(menuModel, "S5");
            ViewBag.MenuTitle = menu[0].TITLE;


            ViewBag.mcode = sMenuCode;


            BoardModel model = new BoardModel
            {
                P_TYPE = "CAP",
                M_CODE = int.Parse(sMenuCode),
                B_NO = int.Parse(sBoardNo)
            };


            List<BoardModel> list = BoardModel.DQL(model, "S1");


            if (list.Count == 1) ViewBag.dataSource = list[0];


            BoardFileModel FileModel = new BoardFileModel { B_NO = int.Parse(sBoardNo) };


            List<BoardFileModel> PopupFilelist = BoardFileModel.DQL(FileModel, "S0");


            ViewBag.PopupFilelist = PopupFilelist;


            ViewBag.ImagePath = FilePath.BasePath;


            return View();
        }
        #endregion




        #region PopupBoardUser
        public ActionResult Detail(string sBoardNo, string sMenuCode)
        {
            MenuModel menuModel = new MenuModel { M_CODE = int.Parse(sMenuCode) };
            List<MenuModel> menu = MenuModel.DQL(menuModel, "S5");
            ViewBag.MenuTitle = menu[0].TITLE;


            BoardModel model = new BoardModel
            {
                P_TYPE = "CAP",
                M_CODE = int.Parse(sMenuCode),
                B_NO = int.Parse(sBoardNo)
            };


            List<BoardModel> list = BoardModel.DQL(model, "S1");


            if (list.Count == 1) ViewBag.dataSource = list[0];


            BoardFileModel FileModel = new BoardFileModel { B_NO = int.Parse(sBoardNo) };


            List<BoardFileModel> PopupFilelist = BoardFileModel.DQL(FileModel, "S0");


            ViewBag.PopupFilelist = PopupFilelist;


            return View();
        }
        #endregion




        #region Save
        public ActionResult EditBoardSave([FromBody] JObject data)
        {
            bool isState = true;


            string sBoardNo = data.SelectToken("BoardNo").ToString();
            string sMenuCode = data.SelectToken("MenuCode").ToString();
            string sTitle = data.SelectToken("Title").ToString();
            string sContent = data.SelectToken("Content").ToString();
            string sUseFile = data.SelectToken("UseFile").ToString();
            string sUserEmail = HttpContext.User.FindFirstValue("Email");


            BoardModel NewData = new BoardModel
            {
                P_TYPE = "CAP",
                B_NO = int.Parse(sBoardNo),
                M_CODE = int.Parse(sMenuCode),
                B_TITLE = sTitle,
                B_CONTENT = sContent,
                USE_FILE = sUseFile,
                EMAIL = sUserEmail
            };


            isState = BoardModel.DML(NewData, "U");


            if (!isState) return Json("A problem occurred during processing. Please try again.");


            if (sUseFile == "Y")
            {
                BoardFileModel OldModel = new BoardFileModel { B_NO = int.Parse(sBoardNo) };
                List<BoardFileModel> OldFiles = BoardFileModel.DQL(OldModel, "S0");


                if (OldFiles.Count > 0)
                {
                    foreach (BoardFileModel oldFile in OldFiles)
                    {
                        BoardFileModel.DML(oldFile, "D");
                    }
                }


                JToken fileToken = data.SelectToken("UploadFile");


                List<BoardFileModel> fileList = BoardFileModel.JObjectToModelList(fileToken);


                foreach (BoardFileModel file in fileList)
                {
                    file.B_NO = int.Parse(sBoardNo);
                    file.FILE_PATH = FilePath.BasePath + $@"\board\{sMenuCode}" + $@"\{file.FILE_NM}.{file.FILE_EXTSN}";


                    isState = BoardFileModel.DML(file, "I");


                    if (!isState) Json("A problem occurred while uploading the files. Please try again.");
                }
            }
            else if (sUseFile == "N")
            {
                BoardFileModel OldModel = new BoardFileModel { B_NO = int.Parse(sBoardNo) };
                List<BoardFileModel> OldFiles = BoardFileModel.DQL(OldModel, "S0");


                if (OldFiles.Count > 0)
                {
                    foreach (BoardFileModel oldFile in OldFiles)
                    {
                        BoardFileModel.DML(oldFile, "D");
                    }
                }
            }


            return Json(null);
        }
        #endregion




        #region Delete
        public IActionResult Delete(string sBoardNo)
        {
            bool isState = true;


            BoardFileModel FileModel = new BoardFileModel { B_NO = int.Parse(sBoardNo) };
            List<BoardFileModel> Filelist = BoardFileModel.DQL(FileModel, "S0");


            if (Filelist.Count > 0)
            {
                foreach (BoardFileModel model in Filelist)
                {
                    isState = BoardFileModel.DML(model, "D");


                    string filePath = model.FILE_PATH;


                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                }
            }


            BoardModel boardModel = new BoardModel { B_NO = int.Parse(sBoardNo) };
            isState = BoardModel.DML(boardModel, "D");


            if (!isState) return Json("A problem occurred during processing. Please try again.");


            return Json(null);
        }
        #endregion




        #region File Download
        public ActionResult DownloadFile(string filePath)
        {
            byte[] fileBytes = System.IO.File.ReadAllBytes(@filePath);


            int backslashCount = filePath.Count(x => x == '\\');
            string fileName = filePath.Split(new char[] { '\\' })[backslashCount];


            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }
        #endregion




        #region Uploader
        [AcceptVerbs("Post")]
        public ActionResult Upload(IList<IFormFile> UploadFiles, string mcode)
        {
            try
            {
                foreach (var file in UploadFiles)
                {
                    if (UploadFiles != null)
                    {
                        var filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');


                        //string sAbsolutePath = Path.GetFullPath(@"Y:\board\");


                        filename = FilePath.BasePath + $@"\board\{mcode}" + $@"\{filename}";
                        //filename = $@"Y:\" + $@"\board\{mcode}" + $@"\{filename}";
                        //filename = sAbsolutePath + $"{mcode}" + $@"\{filename}";


                        var filepath = FilePath.BasePath + $@"\board\{mcode}";
                        //var filepath = $@"Y:\" + $@"\board\{mcode}";
                        //var filepath = sAbsolutePath + $"{mcode}";


                        if (!Directory.Exists(filepath))
                        {
                            Directory.CreateDirectory(filepath);
                        }


                        if (!System.IO.File.Exists(filename))
                        {
                            using (FileStream fs = System.IO.File.Create(filename))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                        }
                        else
                        {
                            System.IO.File.Delete(filename);


                            using (FileStream fs = System.IO.File.Open(filename, FileMode.Append))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }


                            Response.Clear();
                            Response.StatusCode = 204;
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File already exists.";
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.StatusCode = 204;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "No Content";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }


            //Response.Headers.Add("filename");
            return Content("");
        }


        [AcceptVerbs("Post")]
        public ActionResult Remove(IList<IFormFile> UploadFiles, string sMenuCode)
        {
            try
            {
                var fileSavePath = FilePath.BasePath + $@"\board\{sMenuCode}" + $@"\{UploadFiles[0].FileName}";


                if (System.IO.File.Exists(fileSavePath))
                {
                    System.IO.File.Delete(fileSavePath);
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.StatusCode = 200;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
            return Content("");
        }




        [AcceptVerbs("Post")]
        public ActionResult RemoveDB(string mcode, string delFileName, string delFileSize, string B_NO)
        {
            string FILE_NM = delFileName.Split(new char[] { '.' })[0];
            string FILE_EXTSN = delFileName.Split(new char[] { '.' })[1];


            BoardFileModel info = new BoardFileModel
            {
                B_NO = Convert.ToInt32(B_NO),
                FILE_NM = FILE_NM,
                FILE_EXTSN = FILE_EXTSN,
                FILE_SIZE = Convert.ToSingle(delFileSize)
            };


            //Delete DB
            bool isDeleteState = BoardFileModel.DeleteFileDB(info);


            if (isDeleteState)
            {
                try
                {
                    var fileSavePath = FilePath.BasePath + $@"\board\{mcode}" + $@"\{delFileName}";


                    if (System.IO.File.Exists(fileSavePath))
                    {
                        System.IO.File.Delete(fileSavePath);
                    }
                }
                catch (Exception e)
                {
                    Response.Clear();
                    Response.StatusCode = 200;
                    Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully";
                    Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
                }
                return Content("");
            }
            else
            {
                throw new Exception("Error");
            }
        }
        #endregion




        #region Image Control
        public void SaveImage(IList<IFormFile> UploadFiles)
        {
            try
            {
                foreach (IFormFile file in UploadFiles)
                {
                    if (UploadFiles != null)
                    {
                        string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        filename = FilePath.BasePath + "\\BoardImage" + $@"\{filename}";


                        // Create a new directory, if it does not exists
                        if (!Directory.Exists(FilePath.BasePath + "\\BoardImage"))
                        {
                            Directory.CreateDirectory(FilePath.BasePath + "\\BoardImage");
                        }


                        if (!System.IO.File.Exists(filename))
                        {
                            using (FileStream fs = System.IO.File.Create(filename))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                            Response.StatusCode = 200;
                        }
                    }
                }
            }
            catch (Exception)
            {
                Response.StatusCode = 204;
            }
        }


        public void RemoveImage(IList<IFormFile> UploadFiles)
        {
            try
            {
                foreach (IFormFile file in UploadFiles)
                {
                    if (UploadFiles != null)
                    {
                        string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        filename = FilePath.BasePath + "\\BoardImage" + $@"\{filename}";


                        if (System.IO.File.Exists(filename))
                        {
                            System.IO.File.Delete(filename);
                        }
                        Response.StatusCode = 200;
                    }
                }
            }
            catch (Exception)
            {
                Response.StatusCode = 204;
            }
        }
        #endregion
    }
}


<FilePath.cs>

namespace CAP.Models
{
    public class FilePath
    {
        //public static string BasePath { get; } = @"\\66.10.53.40\cap" ;
        public static string BasePath { get; } = @"D:\KimHyunJae\_Project\6. CAP\1. Source\CAP\wwwroot";
    }
}



4 Replies

BS Buvana Sathasivam Syncfusion Team April 22, 2022 04:04 AM UTC

Hi TaeWook,


Greetings from Syncfusion support.


Currently, we are checking your reported issue with high priority. We will update you with further details on or before April 25, 2022.


Regards,

Buvana S




VJ Vinitha Jeyakumar Syncfusion Team April 25, 2022 10:43 AM UTC

Hi TaeWook,


We have created a sample as per your requirement to set the path to store the image in specific location. please check the code and sample below,

Code snippet:
index.cshtml
<ejs-richtexteditor id="editor">
    <e-richtexteditor-insertimagesettings saveUrl="/Home/SaveImage" path="./Uploads/"></e-richtexteditor-insertimagesettings>
</ejs-richtexteditor>
Homecontroller.cs
 [AcceptVerbs("Post")]
        public void SaveImage(IList<IFormFile> UploadFiles)
        {
            try
            {
                foreach (IFormFile file in UploadFiles)
                {
                    if (UploadFiles != null)
                    {
                        string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        filename = hostingEnv.WebRootPath + "\\Uploads" + $@"\{filename}";

                        // Create a new directory, if it does not exists
                        if (!Directory.Exists(hostingEnv.WebRootPath + "\\Uploads"))
                        {
                            Directory.CreateDirectory(hostingEnv.WebRootPath + "\\Uploads");
                        }

                        if (!System.IO.File.Exists(filename))
                        {
                            using (FileStream fs = System.IO.File.Create(filename))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                            Response.StatusCode = 200;
                        }
                    }
                }
            }
            catch (Exception)
            {
                Response.StatusCode = 204;
            }
        }


Regards,
Vinitha


TK TaeWook Kang April 25, 2022 11:55 PM UTC

I want to bring up the image through the absolute path. The sample you gave me doesn't help me with the route I want.



VJ Vinitha Jeyakumar Syncfusion Team April 26, 2022 10:45 AM UTC

Hi TaeWook,


By default, when inserting the image, it is inserted as blob format, the images can be uploaded to the server using the ‘SaveUrl’ property, and the ‘Path‘ property specifies the location to store the images. You can change the ‘Path’ property to change the location of the image stored. 

We want to let you know that the saved images will show the relative path in the source element, and we cannot access the absolute path, and this is a security restriction built into browsers. 


But you can pass the hosted link to the path property to get the absolute path in the source.

Code snippet:
<ejs-richtexteditor id="editor">
    <e-richtexteditor-insertimagesettings saveUrl="/Home/SaveImage" path="https://localhost:7020/Uploads/"></e-richtexteditor-insertimagesettings>
</ejs-richtexteditor>

If we misunderstood your requirements, please provide some more information about the scenario or a runnable sample to further validate on our end.

Regards,
Vinitha.

Loader.
Up arrow icon