Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

支持将图片直接上传到S3等图床(理论上支持所有的django-storage 支持的图床) #168

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
- Full-featured: Real-time Preview, Image (cross-domain) upload, Preformatted text/Code blocks/Tables insert, Search replace, Themes, Multi-languages;
- Markdown Extras : Support ToC (Table of Contents), Emoji;
- Support TeX (LaTeX expressions, Based on KaTeX), Flowchart and Sequence Diagram of Markdown extended syntax;
- Upports uploading images (or files) directly to AWS S3 or any other storage which compatible with S3 API.
- Can constom Editor.md toolbar
- The MDTextField field is provided for the model and can be displayed directly in the django admin.
- The MDTextFormField is provided for the Form and ModelForm.
Expand All @@ -40,6 +41,8 @@
pipenv install django-mdeditor
# or
pip install django-mdeditor
# install `django-storage` if you use upload_to_s3 function.
# pip install django-mdeditor django-storage
```

- Add `mdeditor` to your INSTALLED_APPS setting like this:
Expand Down Expand Up @@ -179,12 +182,20 @@ class ExampleModelAdmin (admin.ModelAdmin):

admin.site.register (demo_models.ExampleModel, ExampleModelAdmin)
```
### Uploading images to S3

Edit `MDEDITOR_CONFIGS` in your settings.py and set `upload_to_S3` to `True`.

Note: Refer to the [django-storage documentation](https://django-storages.readthedocs.io/en/latest/) for `django-storage` setup.

### Customize the toolbar

Add the following configuration to `settings`:
```python
MDEDITOR_CONFIGS = {
'default':{
'upload_to_S3': False, # upload images to s3 (using django-storage)
's3_check_existence': True, # check the image existence before uploading it to s3.
'width': '90% ', # Custom edit box width
    'height': 500, # Custom edit box height
    'toolbar': ["undo", "redo", "|",
Expand Down
13 changes: 12 additions & 1 deletion README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
- 支持实时预览、图片上传、格式化代码、搜索替换、皮肤、多语言等。
- 支持TOC 目录和表情;
- 支持 TeX, 流程图、时序图等图表扩展。
- 支持将图片上传到 AWS S3 或者其他兼容S3 API 的云图床。
- 可自定义 Editor.md 工具栏。
- 提供了 `MDTextField` 字段用来支持模型字段使用。
- 提供了 `MDTextFormField` 字段用来支持 `Form` 和 `ModelForm`.
Expand All @@ -37,6 +38,8 @@
- 安装
```bash
pip install django-mdeditor
# 如果使用 S3,则需要安装 `django-storage`
# pip install django-mdeditor django-storage
```

- 在 `settings` 配置文件 `INSTALLED_APPS` 中添加 `mdeditor`:
Expand Down Expand Up @@ -162,7 +165,7 @@ class MDEditorModleForm(forms.ModelForm):
class Meta:
model = ExampleModel
fields = '__all__'
```
```

### 在 admin 中使用 markdown 小组件

Expand All @@ -185,12 +188,20 @@ class ExampleModelAdmin(admin.ModelAdmin):
admin.site.register(demo_models.ExampleModel, ExampleModelAdmin)
```

### 将图片上传到S3

在settings 中修改 `'upload_to_S3': True,` 启用图床即可。

备注: 有关`django-storage` 的设置部分,请查看 [django-storage 文档](https://django-storages.readthedocs.io/en/latest/)。

### 自定义工具栏

在 `settings` 中增加如下配置 :
```python
MDEDITOR_CONFIGS = {
'default':{
'upload_to_S3': False, # 将图片直接上传到图床。(需要先设置好django-storage)
's3_check_existence': True, # 上传之前是否检查同名文件,若图床中已有同名文件则直接返回,不必上传。(默认为True)
'width': '90%', # 自定义编辑框宽度
'heigth': 500, # 自定义编辑框高度
'toolbar': ["undo", "redo", "|",
Expand Down
40 changes: 34 additions & 6 deletions mdeditor/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from .configs import MDConfig
from storages.backends.s3boto3 import S3StaticStorage

# TODO 此处获取default配置,当用户设置了其他配置时,此处无效,需要进一步完善
MDEDITOR_CONFIGS = MDConfig('default')
Expand Down Expand Up @@ -60,12 +61,39 @@ def post(self, request, *args, **kwargs):
file_full_name = '%s_%s.%s' % (file_name,
'{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now()),
file_extension)
with open(os.path.join(file_path, file_full_name), 'wb+') as file:
for chunk in upload_image.chunks():
file.write(chunk)

# check editor configuration
if MDEDITOR_CONFIGS.get("upload_to_S3"):
# check if the user has uploaded the same image already exists in the S3 bucket
if MDEDITOR_CONFIGS.get("s3_check_existence"):
file_full_name_s3 = '%s.%s' % (file_name, file_extension)
else:
file_full_name_s3 = file_full_name

s3_file_name = \
settings.MEDIA_URL.split('/')[1] + \
'/' \
+ MDEDITOR_CONFIGS['image_folder'] + \
'/' \
+ file_full_name_s3

# get S3 configurations for boto3
storage = S3StaticStorage()

# file already exists
if storage.exists(s3_file_name):
url = storage.url(s3_file_name)
else:
saved = storage.save(name=s3_file_name, content=upload_image)
url = (settings.AWS_S3_ENDPOINT_URL + '/' + settings.AWS_STORAGE_BUCKET_NAME + '/' + saved)
else:
with open(os.path.join(file_path, file_full_name), 'wb+') as file:
for chunk in upload_image.chunks():
file.write(chunk)
url = os.path.join(settings.MEDIA_URL,
MDEDITOR_CONFIGS['image_folder'],
file_full_name)

return JsonResponse({'success': 1,
'message': "上传成功!",
'url': os.path.join(settings.MEDIA_URL,
MDEDITOR_CONFIGS['image_folder'],
file_full_name)})
'url': url})