开发者

How to do httpPost to a webservice which accepts a byte array of a file using c#

开发者 https://www.devze.com 2023-03-07 02:51 出处:网络
I am working on an API kind of project, I have wrote a WebMethod (not exactly. I am using MVC to create REST like API)

I am working on an API kind of project,

I have wrote a WebMethod (not exactly. I am using MVC to create REST like API)

public UploadFileImage(string employeeId, byte[] imageBytes, string imageName)
{
    // saves the imagebyte as an image to a folder
}

the web service would be consumed by a web app, or windows or even iphone or such portable stuffs. I am testing my web service using a web app, by simple httpPost.

string Post(Uri RequestUri, string Data)
    {
        try
        {
            HttpWebRequest request = HttpWebRequest.Create(RequestUri) as HttpWebRequest;

            request.Method = "POST";

            request.ContentType = IsXml.Checked ? "text/xml" : "application/x-www-form-urlencoded";

            byte[] bytes = Encoding.ASCII.GetBytes(Data);
            Stream os = null; // send the Post
            request.ContentLength = bytes.Length;   //Count bytes to send
            os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);

            HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
            StreamReader streamReader = new StreamReader(request.GetResponse开发者_如何学Go().GetResponseStream());
            return streamReader.ReadToEnd();

        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

This code works fine for evey method like, AddEmployee, DeleteEmployee etc. THe parameter Data is of form "Id=123&name=abcdefgh&desig=Developer",

How I call any other function is Post(new Uri("http://localhost/addemployee"),"name=abcd&password=efgh")

where post is the function i wrote.

All good for all functions. Except that I dont know how to consume the above mentioned function UploadFileImage to upload an image?

Thanks


Try encoding the imageBytes as Base64.


From your code snippet is not too clear how you call UploadFileImage, that is how you convert its parameters tripplet into Data.

That is why my answer is quite generic:

In general, you'd better transfer your image file by

request.ContentType = "multipart/form-data; boundary=----------------------------" + DateTime.Now.Ticks.ToString("x");

Please allow me to refer you to a sample at StackOverflow on how to format a multipart request. I am sure that if you google, you shall find a lots of detailed examples and explanations as well.

I hope this helps :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号