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

使用C#生成QRCode并返回React前端供下载的技术求助

解决方案:C#后端生成QRCode并返回React前端下载

后端C#实现(ZXing.Net)

首先确保安装必要的NuGet包:

  • ZXing.Net:核心二维码生成库
  • System.Drawing.Common:用于将PixelData转换为PNG流(Windows/Linux环境均需,Linux下需额外安装libgdiplus)

以下是控制器的完整实现:

using Microsoft.AspNetCore.Mvc;
using ZXing;
using ZXing.QrCode;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

[ApiController]
[Route("api/qrcode")]
public class QrCodeController : ControllerBase
{
    [HttpGet("generate")]
    public IActionResult GenerateQrCode([FromQuery] string url)
    {
        if (string.IsNullOrWhiteSpace(url))
        {
            return BadRequest("请提供有效的URL");
        }

        // 配置二维码生成参数
        var writer = new BarcodeWriterPixelData
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new QrCodeEncodingOptions
            {
                Width = 300,
                Height = 300,
                Margin = 2,
                CharacterSet = "UTF-8", // 支持中文或特殊字符URL
                DisableECI = true
            }
        };

        // 生成二维码像素数据
        var pixelData = writer.Write(url);

        // 转换为PNG字节流
        using var ms = new MemoryStream();
        using var bitmap = new Bitmap(pixelData.Width, pixelData.Height);
        var bitmapData = bitmap.LockBits(
            new Rectangle(0, 0, pixelData.Width, pixelData.Height),
            ImageLockMode.WriteOnly,
            PixelFormat.Format32bppArgb);
        
        System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
        bitmap.UnlockBits(bitmapData);
        bitmap.Save(ms, ImageFormat.Png);
        ms.Position = 0;

        // 返回可下载的文件流
        return File(ms, "image/png", $"二维码_{DateTime.Now:yyyyMMddHHmmss}.png");
    }
}

React前端下载实现

通过fetch请求后端接口,将返回的Blob转换为可下载链接:

import React from 'react';

const QrCodeDownloader = () => {
    const handleDownloadQr = async () => {
        // 替换为你的动态生成URL
        const targetUrl = "https://your-app.com/user/123";
        try {
            const res = await fetch(
                `/api/qrcode/generate?url=${encodeURIComponent(targetUrl)}`,
                { method: 'GET' }
            );

            if (!res.ok) throw new Error('二维码生成失败');

            const blob = await res.blob();
            const downloadUrl = window.URL.createObjectURL(blob);
            
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = '我的二维码.png';
            document.body.appendChild(link);
            link.click();
            
            // 清理资源
            window.URL.revokeObjectURL(downloadUrl);
            document.body.removeChild(link);
        } catch (err) {
            console.error(err);
            alert('下载失败,请稍后重试');
        }
    };

    return (
        <button onClick={handleDownloadQr} style={{padding: '8px 16px'}}>
            下载二维码
        </button>
    );
};

export default QrCodeDownloader;

常见问题排查

  • NuGet包缺失:确认已安装ZXing.Net和System.Drawing.Common,Linux服务器需安装libgdiplus依赖(Ubuntu下apt-get install libgdiplus)
  • URL参数异常:前端传递URL必须用encodeURIComponent转义,避免特殊字符导致参数截断
  • 响应头配置错误:后端返回FileResult时需指定正确的Content-Type为image/png,确保浏览器识别为图片文件
  • 跨域问题:若前后端域名不同,后端需配置CORS策略允许前端域名的GET请求
  • 生成参数错误:检查QrCodeEncodingOptions的宽高、字符集,确保URL长度在二维码容量范围内(QR Code版本决定容量)

内容的提问来源于stack exchange,提问作者Lucca Giffoni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:10:53