summernote:
链接:https://summernote.org/deep-dive/
基于Bootstrap轻量级富文本框,支持直接粘贴图片,开发文档也比较全。
基本使用请自己查阅。
js:
$('#editor').summernote({
height: 250,
1000,
callbacks: {
onImageUpload: function(files, editor, $editable) {
sendFile(files);
}
}
});
function sendFile(files, editor, $editable) {
var size = files[0].size;
console.log(files[0]);
if((size / 1024 / 1024) > 2) {
alert("图片大小不能超过2M...");
return false;
}
var data= new FormData();
data.append("ajaxTaskFile", files[0]);
$.ajax({
data : data,
type : "POST",
url : “”,
cache : false,
contentType : false,
processData : false,
success: function(data) {
$('#summernote').summernote('insertImage',data.pathname );
},
error:function(){
alert("上传失败");
}
});
}
重写内置的上传图片函数。
models:
class TestFile(models.Model):
objectID = models.ForeignKey(TestBug, on_delete=models.CASCADE, blank=True, null=True)
objectType = models.CharField(verbose_name=u'对象类型', max_length=20, blank=False, default='bug')
pathname = models.FileField(verbose_name=u'路径', upload_to='front_static/assets/image')
addedBy = models.CharField(verbose_name=u'创建者', max_length=20, blank=False, default='')
title = models.CharField(verbose_name=u'图片标题', max_length=40, blank=False)
extension = models.CharField(verbose_name=u'后缀', max_length=20, blank=False)
class Meta:
db_table = 't_test_file'
Serializer:
class TestFileSerializer(serializers.ModelSerializer):
bug_name = ReverseRelated(source='objectID.title', many=False, read_only=True)
class Meta:
model = TestFile
fields = ('id', 'objectID', 'objectType', 'pathname', 'title', 'extension', 'bug_name' , 'addedBy')
views:
class SaveFile(viewsets.ModelViewSet):
authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)
queryset = TestFile.objects.all()
serializer_class = TestFileSerializer
def create(self, request, *args, **kwargs):
self.serializer_class = TestFileSerializer
cn_name = request.COOKIES['cn_name']
data = {
"objectType": 'bug',
"pathname": request.data['ajaxTaskFile'],
"addedBy": urlunquote(cn_name),
"title": 'shhs',
"extension": 'jpg'
}
serial = TestFileSerializer(data=data)
if not serial.is_valid():
return Response(serial.data,status=status.HTTP_400_BAD_REQUEST)
serial.save()
return Response(serial.data)
这样的结果只是开发环境,图片会保存到本地服务器,保存之后大致是这样的
如果你需要在本地通过API访问,参考一下配置
STATIC_URL = '/front_static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "front_static"),
)
urlpatterns = [
] + static( settings.STATIC_URL, document_root='front_static/' )
后续会上传到ftp服务器。根据不同项目不同用户创建不同目录保存。