在SQL Server中存储图像

时间:2019-06-13 13:02:19

标签: sql sql-server image

我需要在SQL Server中创建一个过程,该过程采用图像的Web URL并将其转换为VARBINARY,然后:将其存储在表“ tblPersons”中的“ personqr_Image”列中。

我创建了一个过程“ getPersonQrCode”,该过程返回唯一QR码的URL(450x450图像),并使用该URL将其转换为VARBINARY数据类型,以便将其存储在SQL DB中。

不幸的是,我还没有真正找到在线解决方案,可能是因为我对这个主题不是很熟悉。

2 个答案:

答案 0 :(得分:1)

您不能仅在TSQL中执行此操作,因为它没有用于浏览Web以及处理HTTP请求和响应的任何功能。如果必须在SQL Server中执行此操作,则需要编写CLR过程。

答案 1 :(得分:0)

这是CLR功能,可让您提交HTTP请求

 public class RestClient
{
    [SqlFunction(DataAccess = DataAccessKind.Read)]
    public static string Submit(string url, string data, string contentType, string 
    method = "POST",
        string httpHeaderCredentials = "")
    {
        try
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | 
            SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            var request = (HttpWebRequest) WebRequest.Create(url);

            //Add header credentials if required
            if (!string.IsNullOrEmpty(httpHeaderCredentials))
            {
                request.Headers.Add("Authorization: " + httpHeaderCredentials);
            }

            request.ContentType = contentType;
            request.Method = method;

            if (request.Method == "PATCH")
            {
                //http://stackoverflow.com/questions/31043195/rest-api-patch-request
                request.ServicePoint.Expect100Continue = false;
            }


            if (method == "POST" || method == "PATCH")
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(data);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            var httpResponse = request.GetResponse();


            using (var responseStream = httpResponse.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        return reader.ReadToEnd().Replace("\n", string.Empty);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            if (SqlContext.Pipe != null)
            {
                SqlContext.Pipe.Send(ex.Message);
            }
        }

        return "";
    }