Skip to main content
 首页 » 编程设计

c#之summernote 上传图片到s3 (asp.net)

2024年02月06日24duanxz

在过去的两周里,我一直在绞尽脑汁想弄清楚这个问题。

Summernote ( https://github.com/HackerWins/summernote ) 是我的首选编辑器,但我需要将图像上传到 S3 而不是保存为 base64,因为这对于数据库来说太大了,等等。在 summernote github 页面上我有找到了这个 ( https://github.com/HackerWins/summernote/issues/72 ),但没有 .net 代码示例。

我可以从我的 asp 网站将文件上传到 S3,我的问题是我应该如何将文件“发送”到我的网络方法,是的,我正在使用网络方法,因为 summernote 代码在某种程度上是在 js 中处理的那asp会懂吗?

我已经尝试发送"file",并在我的服务器端将其作为对象接收,但这只会导致收到“[object File]”字符串。

我在 VB 中编码,但 C# 代码也将受到赞赏!

提前致谢。

请您参考如下方法:

我不懂任何 VB,所以我希望这段 C# 代码能帮到你。

首先,我从未使用过 amazon-s3,因此我不会提供具体示例,但是在进行快速搜索时,我发现了另一个线程,其中用户指出了如何实际将图像上传到亚马逊使用内存流 here .

一个选项是在服务器端创建一个上传操作,这里是使用 MVC 的 C# 代码片段:

    [HttpPost] 
    public ActionResult UploadImage(HttpPostedFileBase file) 
    { 
        // TODO: your validation goes here,  
        // eg: file != null && file.ContentType.StartsWith("image/") etc... 
 
        var imageUrl = _myAmazonWrapper.UploadImage(file.InputStream); 
 
        return Json(imageUrl); 
    } 

此操作结果将收到一个 HttpPostedFileBase 图像,其中包含具有内容类型、文件名等的实际图像。

最后剩下的就是summernote脚本的实际初始化了:

    $('#summernote').summernote({ 
        onImageUpload: uploadImages 
    }); 

uploadImages 函数定义如下:

var uploadImages = function (files, editor, $editable) { 
 
    var formData = new FormData(); 
    formData.append("file", files[0]); 
 
    $.ajax({ 
        url: "Image/UploadImage", 
        data: formData, 
        type: 'POST', 
        cache: false, 
        contentType: false, 
        processData: false, 
        success: function (imageUrl) { 
 
            if (!imageUrl) { 
 
                // handle error 
 
                return; 
            } 
 
            editor.insertImage($editable, imageUrl); 
        }, 
        error: function () { 
 
            // handle error 
        } 
    }); 
}; 

请注意,uploadImage 函数不支持多张图片,例如,您可以将图片拖放到 summernote 小部件,在这种情况下,"file"参数将包含多张图片,因此只需枚举它们并上传随你便。

祝你好运!