Asp.Net Core 网站使用TinyMCE实现上传图片
阅读原文时间:2023年07月10日阅读:1

1、下载TinyMCE

https://www.tiny.cloud/get-tiny/self-hosted/

解压缩后放在网站wwwroot目录

2、下载中文语言包

https://www.tiny.cloud/get-tiny/language-packages/

解压缩后放在langs目录

3、添加Razor页面

指定images_upload_url参数,实现图片文件的上传功能。此路径指向的地址为步骤4中创建Controller
指定language,语言使用中文简体。

@page
@model CourseAssistant.Pages.TinyMCE.IndexModel
@{
}

4、添加UploadController.cs

using Microsoft.AspNetCore.Mvc;
using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace CourseAssistant.Pages.TinyMCE
{
[Route("TinyMCE/[controller]")]
public class UploadController : Controller
{
IHostingEnvironment hostingEnvironment;
public UploadController(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public string Post()
{
var files = Request.Form.Files;
if (files.Count==0)
{
return "No File";
}
var file = files[0];
var path = hostingEnvironment.WebRootPath;
var UploadDir = "UploadFiles";
var fulldir = Path.Combine(path, UploadDir);
if (!Directory.Exists(fulldir)) Directory.CreateDirectory(fulldir);
var filename = file.FileName;
var fullpath = Path.Combine(path, UploadDir, filename);
using (var fs=new FileStream(fullpath, FileMode.Create, FileAccess.Write))
{
file.CopyTo(fs);
fs.Close();
}
var url = $"/{UploadDir}/{filename}";
var fi = new fileinfo() { location = url };
var s = fi.ToString();
return s;
}
}
public class fileinfo:JsonObject
{
public string location { get; set; }
}
}