Python中文
首页
教程
问答
标签
搜索
登录
注册
在Django中上载图像:“utf8”编解码器无法解码位置246中的字节0x89:无效的开始字节
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我尝试使用纯json在api中上载图像,但当我尝试在request.Files中上载图像并在request.body中上载令牌时,我遇到以下错误:</p> <pre><code>UnicodeDecodeError at /api/auth/set-profile-image/ 'utf-8' codec can't decode byte 0x89 in position 246: invalid start byte </code></pre> <p>上面写着:</p> <pre><code>Unicode error hint The string that could not be encoded/decoded was: " �PNG </code></pre> <p>但我正在发送JPG!:D</p> <p>View.py</p> <pre class="lang-py prettyprint-override"><code>@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 } </code></pre> <p>Form.py</p> <pre class="lang-py prettyprint-override"><code>from django import forms class UploadImage(forms.Form): image = forms.ImageField() </code></pre> <p>我的测试代码是:</p> <pre class="lang-py prettyprint-override"><code>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() </code></pre> <p>我正在models.py中使用<code>ImageField</code>作为我的db字段</p> <p>致以最热烈的问候, 可怜的维护人员被其他代码卡住了</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>图像将包含在UTF-8中表示不安全的数据。如果需要以这种方式传输图像数据,则应首先将其编码为其他在UTF-8中安全的格式,例如base64</p> <p>要在Python发送器中实现这一点,可以使用类似<code>base64.b64encode(img)</code></p> <p>要在另一端再次解码,需要使用<code>base64.b64decode(img)</code></p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
jupyter运行一个旧的pytorch版本
3 回答
Jupyter运行不同版本的卸载库?
2 回答
Jupyter运行指定的键盘快捷键
6 回答
Jupyter通过.local文件“逃逸”virtualenv。我该如何缓解这种情况?
5 回答
Jupyter重新加载自定义样式
8 回答
Jupyter错误:“没有名为Jupyter_core.paths的模块”
4 回答
jupyter错误:无法在随机林中将决策树视为png
1 回答
Jupyter错误'内核似乎已经死亡,它将自动重新启动'为一个给定的代码块
9 回答
Jupyter错误地用阿拉伯语和字母数字元素显示Python列表
9 回答
Jupyter隐藏数据帧索引,但保留原始样式
5 回答
Jupyter集线器:启动器中出现致命错误。。。系统找不到指定的文件
1 回答
Jupyther中相同值的相同哈希,但导出到Bigquery时不相同
1 回答
Jupy上Python的读/写访问问题
2 回答
jupy上没有模块cv
1 回答
Jupy上的排序错误
8 回答
Jupy中bqplot图形的紧凑布局
8 回答
Jupy中matplotlib plot的连续更新
1 回答
Jupy中Numpy函数的文档
8 回答
Jupy中Pandas的自动完成问题
1 回答
jupy中Qt后端的Matplotlib动画
10 回答