You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django后端生成二维码并无服务器存储传输至React前端的实现问题

Django后端生成二维码并无服务器存储传输至React前端的实现问题

Hey there! Let's work through this QR code transfer issue together. I see you've tried a few approaches already, and you're close—let's fix the frontend conversion part and get that QR code displaying properly.

The Root of the Issue

When you switched to base64 encoding, you correctly generated a valid base64 string (since CyberChef could decode it to a working QR). The problem was in how you converted that base64 string back to an image in React: using atob gives you a string, but converting that directly to a Blob doesn't preserve the correct binary data because strings use UTF-16 encoding, while the image bytes are UTF-8.

Simplest Solution: Use Data URIs Directly

Instead of messing with Blobs, you can use the base64 string directly as a data URI in the <img> tag. Browsers support this natively, and it's way simpler.

Step 1: Fix the Backend (Already Done, But Let's Confirm)

Your base64 generation code is correct—make sure you're encoding the image properly and returning it as a string:

import base64
from io import BytesIO
# ... your existing code ...

img.save(img_data, format="PNG")  # Explicitly set format to PNG
img_data.seek(0)
base64_img = base64.b64encode(img_data.getvalue()).decode('utf-8')
return Response({"qr": base64_img}, status=status.HTTP_200_OK)

Note: Adding format="PNG" ensures the image is saved in the correct format, which avoids any ambiguity.

Step 2: Update the Frontend to Use Data URI

Instead of converting to Blob, just prepend the base64 string with the data URI prefix and use it directly as the image source:

const generateQRCode = async () => {
  try {
    const response = await axios.get(`${API_SOFTWARE}${id}/genQR`);
    // Construct the data URI for PNG image
    const qrDataUri = `data:image/png;base64,${response.data.qr}`;
    setQRCode(qrDataUri);
  } catch (err) {
    console.log("Error in generating QR code", err);
  }
};

Then your existing <img> tag will work perfectly:

{QRCode && <img src={QRCode} alt="Product QR Code" />}

Alternative: Correct Blob Conversion (If You Prefer Blobs)

If you still want to use Blobs for some reason, you need to convert the base64 string to a Uint8Array first to preserve the binary data:

const generateQRCode = async () => {
  try {
    const response = await axios.get(`${API_SOFTWARE}${id}/genQR`);
    const base64String = response.data.qr;
    // Decode base64 to binary string
    const binaryString = atob(base64String);
    // Convert binary string to Uint8Array
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    // Create Blob with correct MIME type
    const blob = new Blob([bytes], { type: 'image/png' });
    const url = URL.createObjectURL(blob);
    setQRCode(url);
  } catch (err) {
    console.log("Error in generating QR code", err);
  }
};

Just remember to revoke the object URL when you're done with it (e.g., in a cleanup function) to avoid memory leaks:

useEffect(() => {
  return () => {
    if (QRCode) {
      URL.revokeObjectURL(QRCode);
    }
  };
}, [QRCode]);

Why Your Initial Binary Approach Failed

When you sent the raw binary data as a string (str(img_binary)), Python converted the bytes to a human-readable string with escape sequences (like \x89PNG), which isn't the same as the raw binary. The frontend couldn't convert this string back to valid image bytes because it had lost the original binary structure. Base64 avoids this by encoding binary data into ASCII characters that can safely be sent in JSON.

That should get your QR code displaying correctly without saving anything to the server. Let me know if you run into any more issues!

备注:内容来源于stack exchange,提问作者lubos-source

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 10:28:08