[英]Django endpoint to upload image fails when submitted from browser but not postman
I'm building a solution that takes screenshots from a web browser and sends it to a django endpoint. 我正在构建一个从Web浏览器获取屏幕截图并将其发送到django端点的解决方案。 The solution works when I use postman to send the information. 当我使用邮递员发送信息时,该解决方案有效。 However when I use my javascript google chrome extension it fails. 但是,当我使用我的javascript Google chrome扩展名时,它会失败。 the information I send is composed of two fields image(text) and dashboard_type(text), 我发送的信息由两个字段image(text)和dashboard_type(text)组成,
views.py views.py
class ScreenShotUpload(APIView):
def post(self, request, format=None):
dashboard_type = request.data.get("dashboard_type", None)
image_str = request.data.get("image", None)
if dashboard_type is None or image_str is None:
return Response({"Error": "invalid entry"}, status.HTTP_400_BAD_REQUEST)
if dashboard_type not in [ScreenShot.SH, ScreenShot.WE, ScreenShot.PA, ScreenShot.PR]:
return Response(
{"Error": "invalid dashboard_type, must be either PA, PR, SH or WE"}, status.HTTP_400_BAD_REQUEST)
ScreenShot.objects.filter(is_latest=True).update(is_latest=False)
new_screenshot = ScreenShot(dashboard_type=dashboard_type, is_latest=True)
new_screenshot.set_image_path()
new_screenshot.save_image_str(image_str)
new_screenshot.save()
return Response({"status": "200"}, status.HTTP_200_OK)
chrome-extension.js 铬extension.js
var id = 100;
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.captureVisibleTab(null, {format: "jpeg", quality: 100}, function(screenshotUrl) {
var xhr = new XMLHttpRequest() , formData = new FormData();
formData.append("image", screenshotUrl);
formData.append("dashboard_type", "SH");
xhr.open("POST", "http://intranet/api/powerbi/screenshots_upload/");
xhr.send(formData);
var viewTabUrl = chrome.extension.getURL('screenshot.html?id=' + id++)
var targetId = null;
});
});
As I wrote above, when I use postman to send the image as a base64 string that represents an image it works but when I use this script it fails(image corrupted) the size of the image is smaller when I send it with the script than postman. 如我上面所写,当我使用邮递员将图像作为表示图像的base64字符串发送时,它可以工作,但是当我使用此脚本时,它失败(图像损坏),与脚本一起发送时图像的尺寸比邮差。 I narrowed down to two possibilities either the xhr request doesn't send the full image or I need to parse the request.data differently. 我缩小了两种可能性,要么xhr请求没有发送完整的图像,要么我需要以不同的方式解析request.data。 Can someone explain what is going on? 有人可以解释发生了什么吗? thank you. 谢谢。
我必须删除data:image / jpeg; base64,我之前曾尝试在字符串上执行replace(“ data:image / jpeg; base64,”,“”),但是使用索引却无法正常工作,例如image_str = image_str [23:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.