在Django使用中我们在返回数据时二进制的图片数据时,需要格外注意单复数的拼写,要不然会导致下载,而不是显示验证码。

class ImgVerifyCodeAPI(APIView):

    def get(self, request, image_code_id):
        # 1.调用captcha生成验证码
        # tuple, (name, text, StringIO.value).
        cap_name, cap_text, cap_img  = captcha.generate_captcha()
        # 此时的content_type是正常的
        return HttpResponse(cap_img, content_type="image/jpg")

下面这种写法会导致浏览器等会默认下载验证码图片

class ImgVerifyCodeAPI(APIView):

    def get(self, request, image_code_id):
        # 1.调用captcha生成验证码
        # tuple, (name, text, StringIO.value).
        cap_name, cap_text, cap_img  = captcha.generate_captcha()
        # 没错就是加了一个s
        return HttpResponse(cap_img, content_type="images/jpg")

更多推荐

Content_type为图片注意点