我正在构建一个解决方案,从Web浏览器获取屏幕截图并将其发送到django端点。当我使用邮递员发送信息时,解决方案有效。但是当我使用我的javascript google chrome扩展程序时,它会失败。我发送的信息由两个字段image(text)和dashboard_type(text)组成,
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)
铬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;
});
});
正如我上面所写的那样,当我使用postman将图像作为base64字符串发送它代表一个图像时它可以工作但是当我使用这个脚本时它失败(图像损坏)当我发送它时图像的大小更小脚本比邮差。我缩小到两种可能性xhr请求不发送完整图像或我需要以不同方式解析request.data。有人可以解释发生了什么吗?谢谢。
答案 0 :(得分:0)
我不得不删除数据:image / jpeg; base64,我之前在字符串上尝试替换(“data:image / jpeg; base64,”,“”),但是我没有使用索引工作,比如像image_str = image_str [23:]