使用WCF Restful服务将图像上传到数据库

发布于 2024-11-03 13:34:29 字数 1735 浏览 0 评论 0原文

我正在使用 WCF Restful 服务将图像上传到我的数据库 代码:

[OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "AddDealImage/{id}")]
        long AddDealImage(string id, Stream image);

public long AddDealImage(string id, Stream image)
        {
            //add convert Stram to byte[]
            byte[] buffer = UploadFile.StreamToByte(image);
            //create image record for database
            Img img = ImgService.NewImage(DateTime.Now.ToFileTime().ToString(), "", buffer, "image/png");
            ImgService.AddImage(img);
            //return image id
            return img.ImageId;
        }

public static byte[] StreamToByte(Stream stream)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

问题: 当我通过 iPhone 上传照片时,POST 成功。返回新的图像 ID,我可以看到数据库中创建的新记录。 但是,当我尝试将二进制从数据库记录转换为图像流时:我收到错误: “找不到适合完成此操作的成像组件。”

似乎 MemoryStream 已损坏。

//photoBytes from database   
MemoryStream photoStream = new MemoryStream(photoBytes)
    //Error happened here
    var photoDecoder = BitmapDecoder.Create(
                    photoStream,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.None);

另外,仅当通过 WCF Restful 服务上传图像时才会发生该错误。 如果图像是通过网络表单上传的,则效果非常好。

问题:

  1. 我哪里做错或者错过了?

  2. 我如何编写一个测试客户端来测试这个上传API?

非常感谢

I am using WCF restful service to upload image to my databse
Code:

[OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "AddDealImage/{id}")]
        long AddDealImage(string id, Stream image);

public long AddDealImage(string id, Stream image)
        {
            //add convert Stram to byte[]
            byte[] buffer = UploadFile.StreamToByte(image);
            //create image record for database
            Img img = ImgService.NewImage(DateTime.Now.ToFileTime().ToString(), "", buffer, "image/png");
            ImgService.AddImage(img);
            //return image id
            return img.ImageId;
        }

public static byte[] StreamToByte(Stream stream)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

Problem:
When i upload my photo via iPhone the POST was Successful. New image id is returned, and I can see the new record created in the database.
However when I try to convert binary from DB record to Image Stream: I got error:
"No imaging component suitable to complete this operation was found."

it seems that the MemoryStream is corrupted.

//photoBytes from database   
MemoryStream photoStream = new MemoryStream(photoBytes)
    //Error happened here
    var photoDecoder = BitmapDecoder.Create(
                    photoStream,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.None);

Plus, the error only happens when image is uploaded via WCF Restful service.
It works perfectly if the image is uploaded via web form.

Question:

  1. Where did i do wrong or missed?

  2. how can i write a test client to test this upload api?

many thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

穿透光 2024-11-10 13:34:29

上面的代码确实有效。
我错过的部分是你需要在 web.config 中将其设置为“Streamed”的transferModel

测试代码:

static void Main()
        {
            string filePath = @"C:\Users\Dizzy\Desktop\600.png";

            string url = "http://localhost:13228/ApiRestful.svc/AddDealImage/96";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "text/xml";
            request.Method = "POST";

            using (Stream fileStream = File.OpenRead(filePath))
            using (Stream requestStream = request.GetRequestStream())
            {
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int byteCount = 0;
                while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    requestStream.Write(buffer, 0, byteCount);
                }
            }

            string result;

            using (WebResponse response = request.GetResponse())
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                result = reader.ReadToEnd();
            }

            Console.WriteLine(result);
        }

the code above actually works.
the part I missed is the transferModel you need to set it to "Streamed" in web.config

Code for testing:

static void Main()
        {
            string filePath = @"C:\Users\Dizzy\Desktop\600.png";

            string url = "http://localhost:13228/ApiRestful.svc/AddDealImage/96";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "text/xml";
            request.Method = "POST";

            using (Stream fileStream = File.OpenRead(filePath))
            using (Stream requestStream = request.GetRequestStream())
            {
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int byteCount = 0;
                while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    requestStream.Write(buffer, 0, byteCount);
                }
            }

            string result;

            using (WebResponse response = request.GetResponse())
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                result = reader.ReadToEnd();
            }

            Console.WriteLine(result);
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文