用于从Raspberry Pi上传到WCF服务的Python客户端

时间:2013-11-25 14:29:53

标签: c# python wcf web-services raspberry-pi

我正在运行一个WCF服务,它接受一个图像文件并将其存储在本地文件系统中。它由控制台应用程序托管,并在本地计算机中运行。代码如下。

Iservice.cs

    [ServiceContract]
    public interface IImageUpload
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "FileUpload/{fileName}")]
        void FileUpload(string fileName, Stream fileStream);

    }

Service.cs

public class ImageUploadService : IImageUpload
    {
        public void FileUpload(string fileName, Stream fileStream)
        {
        FileStream fileToupload = new FileStream("C:\\ImageProcessing\\Images\\Destination\\" + fileName, FileMode.Create);
        byte[] bytearray = new byte[5000000];
        int bytesRead, totalBytesRead = 0;
        do
        {
            bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
            totalBytesRead += bytesRead;
        } while (bytesRead > 0);
        fileToupload.Write(bytearray, 0, bytearray.Length);
        fileToupload.Close();
        fileToupload.Dispose();

    }
}

console program.cs to host

static void Main(string[] args)
    {
        string baseAddress = "http://192.168.1.4:8000/Service";
        WebHttpBinding wb = new WebHttpBinding();
        wb.MaxBufferSize = 4194304;
        wb.MaxReceivedMessageSize = 4194304;
        wb.MaxBufferPoolSize = 4194304;

        ServiceHost host = new ServiceHost(typeof(ImageUploadService), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(IImageUpload), wb, "").Behaviors.Add(new WebHttpBehavior());
        //host.AddServiceEndpoint(typeof(IImageUpload), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");
        Console.ReadKey(true);
    }

现在我有了一个C#客户端,它只是一个简单的窗体,上面有一个按钮可以与这个服务进行对话。它从本地系统获取文件并将其发送到服务。代码如下。

 private void button1_Click(object sender, EventArgs e)
    {
        byte[] bytearray = null;

        string name = "PictureX.jpg";

        Image im = Image.FromFile("C:\\ImageProcessing\\Images\\Source\\Picture1.jpg"); // big file

        bytearray = imageToByteArray(im);

        string baseAddress = "http://192.168.1.4:8000/Service/FileUpload/";
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress + name);
        request.Method = "POST";
        request.ContentType = "text/plain";
        request.ContentLength = bytearray.Length;

        Stream serverStream = request.GetRequestStream();
        serverStream.Write(bytearray, 0, bytearray.Length);
        serverStream.Close();
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            int statusCode = (int)response.StatusCode;
            StreamReader reader = new StreamReader(response.GetResponseStream());
        }
    }

    public byte[] imageToByteArray(Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        return ms.ToArray();
    }

当我在同一台笔记本电脑内的独立视觉工作室上运行时,它们都工作正常。我的服务中没有app.config或web.config。一切都写在代码中。 可以在以下链接中找到整个代码。 https://github.com/logrcubed/ImageprocessingAlgorithm_WCF

现在我将覆盆子pi连接到相同的WiFi(读取本地LAN)并想要编写一个python脚本,将图像从Pi中的本地文件夹上传到类似于我的C#客户端的WCF服务。 * 如何实现这一目标?完成这项工作的python代码是什么? 我是python的新手。所以任何帮助都表示赞赏。 *

我尝试了以下方法作为命中和试用,其中大部分都给出了404错误。我不明白这些是否正确。任何人都可以帮助我将C#中的webrequest转换为python吗? 海报库

# test_client.py
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2

# Register the streaming http handlers with urllib2
register_openers()

# Start the multipart/form-data encoding of the file "DSC0001.jpg"
# "image1" is the name of the parameter, which is normally set
# via the "name" parameter of the HTML <input> tag.

# headers contains the necessary Content-Type and Content-Length
# datagen is a generator object that yields the encoded parameters
datagen, headers = multipart_encode({"image1": open("/home/pi/test.jpg", "rb")})

# Create the Request object
request = urllib2.Request("http://192.168.1.6:8000/Service/", datagen, headers)
# Actually do the request, and get the response
print urllib2.urlopen(request).read()

的urllib2

import urllib2
import MultipartPostHandler
params = {'file':open( "/home/pi/test.jpg" , 'rb')}
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
req = urllib2.Request( "http://192.168.1.6:8000/Service/FileUpload" , params)
text_response = urllib2.urlopen(req).read().strip()

请求

import requests

url = 'http://192.168.1.4:8000/Service'
headers = {'content-type': 'text/plain'}
files = {'file': open('/home/pi/test.jpg', 'rb')}
r = requests.post(url, files=files, headers=headers)

0 个答案:

没有答案