python django前后端分离图片上传
时间: 2023-07-25 12:32:11 浏览: 57
若要实现前后端分离的图片上传,可以使用以下步骤:
1. 前端使用表单上传图片,将图片转换成 base64 编码的字符串,并将该字符串作为参数发送给后端。
2. 后端接收前端发送的 base64 编码的字符串,并将其转换为图片文件。
3. 后端将转换后的图片文件存储到指定的文件夹中,并生成图片的路径。
4. 后端将图片路径返回给前端,前端再将该路径存储到数据库中。
下面是一个简单的示例:
前端代码:
```html
<input type="file" accept="image/*" onchange="uploadImage(event)">
```
```javascript
function uploadImage(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
const data = reader.result;
axios.post('/api/upload-image', { image: data })
.then(response => {
const imageUrl = response.data.imageUrl;
// 将 imageUrl 存储到数据库中
})
.catch(error => {
console.log(error);
})
}
}
```
后端代码:
```python
import base64
import os
from django.conf import settings
from django.http import JsonResponse
def upload_image(request):
if request.method == 'POST':
image_data = request.POST.get('image')
image_data = base64.b64decode(image_data.split(',')[1])
image_name = 'image.jpg'
image_path = os.path.join(settings.MEDIA_ROOT, image_name)
with open(image_path, 'wb') as f:
f.write(image_data)
image_url = os.path.join(settings.MEDIA_URL, image_name)
return JsonResponse({'imageUrl': image_url})
```
需要注意的是,上述示例仅做参考,具体实现应根据实际情况进行调整。同时,在实际应用中还需考虑图片大小限制、图片格式限制等问题。