# image_upload
**Repository Path**: fengfengzhidao/image_upload
## Basic Information
- **Project Name**: image_upload
- **Description**: 图片上传的三种方式
- **Primary Language**: Python
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: http://www.fengfengzhidao.com
- **GVP Project**: No
## Statistics
- **Stars**: 3
- **Forks**: 1
- **Created**: 2022-02-16
- **Last Updated**: 2024-07-26
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# 枫枫知道
枫枫知道,一个爱好写文章的程序员
[项目介绍](#项目介绍) |
[网站截图](#网站截图) |
[运行项目](#运行项目) |
## 项目介绍
图片上传的几种方式
- 直接上传到文件夹
- 通过django上传到数据库
- 复制粘贴上传
- 拖拽上传
## 网站截图



## 运行项目
```python
1. 创建虚拟环境
2. 安装项目所需的第三方模块
3. 运行项目即可
```
## 核心代码
```javascript
edit_photo(e) {
let clipboardData = (e.clipboardData || e.originalEvent.clipboardData);
let items = clipboardData.items, len = items.length, blob = null;
//阻止默认行为即不让剪贴板内容在div中显示出来
e.preventDefault();
//在items里找粘贴的image,据上面分析,需要循环
for (let i = 0; i < len; i++) {
if (items[i].type.indexOf("image") !== -1) {
//getAsFile() 此方法只是living standard firefox ie11 并不支持
blob = items[i].getAsFile();
}
}
if (blob !== null) {
// 读取图片文件
let reader = new FileReader();
reader.onload = function (event) {
// event.target.result 即为图片的Base64编码字符串
let base64_str = event.target.result
//可以在这里写上传逻辑 直接将base64编码的字符串上传(可以尝试传入blob对象,看看后台程序能否解析)
uploadImgFromPaste(base64_str);
}
reader.readAsDataURL(blob);
}
}
// 将base64的图片上传到服务器
function uploadImgFromPaste(file) {
$.post('/upload_image_by_paste/', {image: file}, res => {
$('#img_list').append(`
`)
})
}
```
base64转图片数据
```python
import base64
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
@csrf_exempt
def upload_image_by_media(request):
from django.core.files.uploadedfile import InMemoryUploadedFile
from io import BytesIO
from app01 import models
img = request.POST.get('image')
res = img.split(',')[1]
img_b64decode = base64.b64decode(res)
# base64转file对象
image = BytesIO(img_b64decode)
file = InMemoryUploadedFile(
file=image, field_name='file', name='图片粘贴.png', content_type='image/png', size='738096',
charset=None)
cover_obj = models.Cover.objects.create(url=file, state=0)
return JsonResponse({'ret': 0, 'msg': 'success', "store_path": cover_obj.url.url})
```