Skip to main content
 首页 » 编程设计

c#之PHP之byte[] 到 Blob

2024年02月06日11zhengyun_ustc

我正在尝试使用 HTTP Post 发送一个 byte[] 作为图像存储到 MySQL 数据库中,但它没有正确编码 byte[] 或者我只是在做一些非常错误的事情。

C#代码

public async Task<string> Post (byte[] image) 
    { 
        string data = data = string.Format ("METHOD=post&Image={0}", image); 
 
        HttpWebRequest r = await Info.createRequest (data); 
        using (var resp = await Task.Factory.FromAsync<WebResponse> (r.BeginGetResponse, r.EndGetResponse, null)) { 
            return "Finished"; 
        } 
    } 
 
/*Info.createRequest(data)*/ 
public static async Task<HttpWebRequest> createRequest (string json, string ContentType = "application/x-www-form-urlencoded", byte[] img = null) 
    { 
        (new CancellationTokenSource ()).Dispose (); 
        var request = WebRequest.Create (BaseUrl) as HttpWebRequest;  
        request.Method = "POST"; 
        request.ContentType = ContentType; 
 
        byte[] postData = Encoding.UTF8.GetBytes (json); 
 
        using (var stream = await Task.Factory.FromAsync<Stream> (request.BeginGetRequestStream, request.EndGetRequestStream, request)) { 
            await stream.WriteAsync (postData, 0, postData.Length); 
            /*if (img != null) 
                await stream.WriteAsync (img, 0, img.Length);*/ 
            //^ Didn't seme to work.  
        } 
 
        return request; 
    } 

PHP 代码

$null = NULL; 
        $stmt = $this->db->prepare("INSERT INTO Posts (Image) VALUES (?)"); 
        $stmt->bind_param("b", $_POST["Image"]); 
        $stmt->execute(); 
        $stmt->close(); 

请您参考如下方法:

string.Format("METHOD=post&Image={0}", image); 

会产生类似的东西:

METHOD=post&Image=System.Byte[] 

所以实际上不会发送任何有用的东西。

您可以使用 Base64 encoding如果你想发布二进制数据:

String base64 = System.Convert.ToBase64String(image) 
string.Format("METHOD=post&Image={0}", base64 ); 

我不确定在 PHP 中如何完成反向操作,但我认为它是使用 base64_decode 的东西:

$base64Image = base64_decode($_POST["Image"]);