我尝试使用纯json在api中上载图像,但当我尝试在request.Files中上载图像并在request.body中上载令牌时,我遇到以下错误:
UnicodeDecodeError at /api/auth/set-profile-image/
'utf-8' codec can't decode byte 0x89 in position 246: invalid start byte
上面写着:
Unicode error hint
The string that could not be encoded/decoded was: " �PNG
但我正在发送JPG!:D
View.py
@csrf_exempt
def set_profile_image(request):
if request.method == 'POST':
request_info = json.loads(request.body)
token = request_info.get('token')
img = request.FILES['image']
if token is not None and img is not None:
user = User.objects.filter(token=token)
if user.exists():
user = user.get()
form = UploadImage(request.POST, request.FILES['image'])
if form.is_valid():
user.profile_image = form.cleaned_data['image']
user.save()
response = {
'status_code': 200,
'image_set': True,
'image_url': user.profile_image.url
}
Form.py
from django import forms
class UploadImage(forms.Form):
image = forms.ImageField()
我的测试代码是:
import requests
data = {
'token': 'helloworld1--_aFsV-ZVG9lVpi0KSydrx3pG3TSMPqqHVKWD2Yc8bE'
}
url = 'http://localhost:8000/api/auth/set-profile-image/'
with open('test.jpg', 'rb') as img:
response = requests.post(
url=url,
data=data,
files={
'image': img
}
)
# print(response.text)
f = open('test.html', 'wb')
f.write(response.content)
f.close()
我正在models.py中使用ImageField
作为我的db字段
致以最热烈的问候, 可怜的维护人员被其他代码卡住了
图像将包含在UTF-8中表示不安全的数据。如果需要以这种方式传输图像数据,则应首先将其编码为其他在UTF-8中安全的格式,例如base64
要在Python发送器中实现这一点,可以使用类似
base64.b64encode(img)
要在另一端再次解码,需要使用
base64.b64decode(img)
好的,经过一些测试,感谢Jacob See的回答,我找到了一个解决方案:
首先,我将图像编码到base64并通过API发送,如下所示:
在我的API中,我执行以下操作:
问题解决:D
相关问题 更多 >
编程相关推荐