您的上传功能应如下所示。这个对我有用。我建议你也可以参考CKEditor FileUpload Helper
。它也应该对你有所帮助。
[HttpPost]
public ActionResult UploadImg(IFormFile upload)
{
if (upload.Length <= 0 ) return null;
// check the upload file is image
if (!System.Drawing.Image.FromStream(upload.OpenReadStream()))
{
dynamic error= JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" pls upload img"\"}}");
return Json(error);
}
var fileName = Guid.NewGuid() + Path.GetExtension(upload.FileName).ToLower();
Image image = Image.FromStream(upload.OpenReadStream());
int width = image.Width;
int height = image.Height;
// limit image size
if ((width > 750) || (height > 500))
{
var error = "The file size is wrong. ";
dynamic msg= JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + error + "\"}}");
return Json(msg);
}
// file size limit, 500k
if (upload.Length > 500 * 1024)
{
var error= "file is too large";
dynamic msg= JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + error+ "\"}}");
return Json(msg);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot/images/CKEditorImages",
fileName);
using (var stream = new FileStream(path, FileMode.Create))
{
upload.CopyTo(stream);
}
var url = $"{"/images/CKEditorImages/"}{fileName}";
var successMessage = "upload successfully";
dynamic success = JsonConvert.DeserializeObject("{ 'uploaded': 1,'fileName': \"" + fileName + "\",'url': \"" + url + "\", 'error': { 'message': \"" + successMessage + "\"}}");
return Json(success);
}