How to post a Multipart http message to a web service in C# and handle it with Java

This post is going to handle the following scenario:

  • Upload a file to a server by sending an HTTP POST to a web service in a multipart form data content type with C#
  • Accept and handle the message in the web service side using Java

I admit this may not be the typical scenario you encounter in your job as a .NET developer; however, as I need to switch between the .NET and the Java world relatively frequently in my job this just happened to be a problem I had to solve recently.

Let’s start with the .NET side of the problem: upload the byte array contents of a file to a server using a web service. We’ll take the following steps:

  • Read in the byte array contents of the file
  • Construct the HttpRequestMessage object
  • Set up the request message headers
  • Set the Multipart content of the request
  • Send the request to the web service
  • Await the response

Start Visual Studio 2012 – the below code samples should work in VS2010 as well – and create a new Console application. We will only work within Program.cs for simplicity.

Step 1: read the file contents, this should be straightforward

private static void SendFileToServer(string fileFullPath)
        {
            FileInfo fi = new FileInfo(fileFullPath);
            string fileName = fi.Name;
            byte[] fileContents = File.ReadAllBytes(fi.FullName);
        }

Step2: Construct the HttpRequestMessage object

The HttpRequestMessage within the System.Net.Http namespace represents exactly what it says: a HTTP request. It is a very flexible object that allows you to specify the web method, the contents, the headers and much more properties of the HTTP message. Add the following code to SendFileToServer(string fileFullPath):

Uri webService = new Uri(@"http://avalidwebservice.com");
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, webService);
requestMessage.Headers.ExpectContinue = false;

The last piece of code, i.e. the one that sets ExpectContinue to false means that the Expect header of the message will not contain Continue. This property is set to true by default. However, a number of servers don’t know how to handle the ‘Continue’ value and they will throw an exception. I ran into this problem when I was working on this scenario so I’ll set it to false. This does not mean that you have to turn off this property every time you call a web service with HttpRequestMessage, but in my case it solved an apparently inexplicable problem.

You’ll obviously need to replace the fictional web service address with a real one.

Step 3: set the multipart content of the http request

You should specify the boundary string of the multipart message in the constructor of the MultipartFormDataContent object. This will set the boundary of the individual parts within the multipart message. We’ll then add a byte array content to the message passing in the bytes of the file to be uploaded. Note that we can add the following parameters to the to individual multipart messages:

  • The content itself, e.g. the byte array content
  • A name for that content: this is ideal if the receiving party needs to search for a specific name
  • A filename that will be added to the content-disposition header of the message: this is a name by which the web service can save the file contents

We also specify that the content type header should be of application/octet-stream for obvious reasons.

Add the following code to SendFileToServer(string fileFullPath):

MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----MyGreatBoundary");
ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
byteArrayContent.Headers.Add("Content-Type", "application/octet-stream");
multiPartContent.Add(byteArrayContent, "this is the name of the content", fileName);
requestMessage.Content = multiPartContent;

Step 4: send the message to the web service and get the response

We’re now ready to send the message to the server by using the HttpClient object in the System.Net.Http namespace. We’ll also get the response from the server.

HttpClient httpClient = new HttpClient();
Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage,    HttpCompletionOption.ResponseContentRead, CancellationToken.None);
HttpResponseMessage httpResponse = httpRequest.Result;

We can send the message using the SendAsync method of the HttpClient object. It returns a Task of type HttpResponseMessage which represents a Task that will be carried out in the future. Note that this call will NOT actually send the message to the service, this is only a preparatory phase. If you are familiar with the Task Parallel Library then this should be no surprise to you – the call to the service will be made upon calling the Result property of the Task object.

This post is not about the TPL so I will not go into any details here – if you are not familiar with the TPL but would like to learn about multipart messaging then read on and please just accept the provided code sample ‘as is’. Otherwise there are a great number of sites on the net discussing the Task object and its workings.


Step 5
: read the response from the server

Using the HttpResponseMessage object we can analyse the service response in great detail: status code, response content, headers etc. The response content can be of different types: byte array, form data, string, multipart, stream. In this example we will read the string contents of the message, again using the TPL. Add the following code to SendFileToServer(string fileFullPath):

HttpStatusCode statusCode = httpResponse.StatusCode;
                HttpContent responseContent = httpResponse.Content;

                if (responseContent != null)
                {
                    Task<String> stringContentsTask = responseContent.ReadAsStringAsync();
                    String stringContents = stringContentsTask.Result;                    
                }

It is up to you of course what you do with the string contents.

Ideally we should include the web service call in a try-catch as service calls can throw all sorts of exceptions. Here the final version of the method:

private static void SendFileToServer(string fileFullPath)
        {
            FileInfo fi = new FileInfo(fileFullPath);
            string fileName = fi.Name;
            byte[] fileContents = File.ReadAllBytes(fi.FullName);
            Uri webService = new Uri(@"http://avalidwebservice.com");
            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, webService);
            requestMessage.Headers.ExpectContinue = false;

            MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----MyGreatBoundary");
            ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
            byteArrayContent.Headers.Add("Content-Type", "application/octet-stream");
            multiPartContent.Add(byteArrayContent, "this is the name of the content", fileName);
            requestMessage.Content = multiPartContent;

            HttpClient httpClient = new HttpClient();
            try
            {
                Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
                HttpResponseMessage httpResponse = httpRequest.Result;
                HttpStatusCode statusCode = httpResponse.StatusCode;
                HttpContent responseContent = httpResponse.Content;

                if (responseContent != null)
                {
                    Task<String> stringContentsTask = responseContent.ReadAsStringAsync();
                    String stringContents = stringContentsTask.Result;                    
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

This concludes the .NET portion of our problem. Let’s now see how the incoming message can be handled in a Java web service.

So you have a Java web service which received the above multipart message. The solution presented below is based on a Servlet with the standard doPost method.

The HttpServletRequest in the signature of the doPost method can be used to inspect the individual parts of the incoming message. This yields a collection which we can iterate through:

@Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Collection<Part> requestParts = request.getParts();
        Iterator<Part> partIterator = requestParts.iterator();
        while (partIterator.hasNext())
        {
        }
    }

If the message is not of type MultipartFormData then the collection of messages will be zero length.

The Part object in the java.servlet.http namespace represents a section in the multipart message delimited by some string token, which we provided in the MultipartFormDataContent constructor. Now our goal is to specifically find the byte array message we named “this is the name of the content” in the .NET code. This name can be extracted using the getName() getter of the Part object. Add the following code to the while loop:

Part actualPart = partIterator.next();
if (actualPart.getName().equals("this is the name of the content"))
{
}

The Part object also offers a getInputStream() method that can be used later to save the byte array in a file. The file name we provided in the C# code will be added to the content-disposition header of the multipart message – or to be exact to the header of the PART of the message. Keep in mind that each individual message within the multipart message can have its own headers. We will need to iterate through the headers of the byte array message to locate the content-disposition header. Add the following to the if clause:

InputStream is = actualPart.getInputStream();
String fileName = "";
Collection<String> headerNames = actualPart.getHeaderNames();
Iterator<String> headerNamesIterator = headerNames.iterator();
while (headerNamesIterator.hasNext())
{
    String headerName = headerNamesIterator.next();
    String headerValue = actualPart.getHeader(headerName);
    if (headerName.equals("content-disposition"))
    {
    }
}

The last step of the problem is to find the file name within the header. The value of the content-disposition header is a collection of comma separated key-value pairs. Within it you will find “filename=myfile.txt” or whatever file name was provided in the C# code. I have not actually found any ready-to-use method to extract exactly the filename so my solution is very a very basic one based on searching the full string. Add the below code within “if (headerName.equals(“content-disposition”))”:

String searchTerm = "filename=";
int startIndex = headerValue.indexOf(searchTerm);
int endIndex = headerValue.indexOf(";", startIndex);
fileName = headerValue.substring(startIndex + searchTerm.length(), endIndex);

So now you have access to all three ingredients of the message:

  • The byte array in form of an InputStream object
  • The name of the byte array contents
  • The file name

The next step would be to save the message in the file system, but that should be straightforward using the ‘read’ method if the InputStream:

OutputStream out = new FileOutputStream(f);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
{
    out.write(buf, 0, len);
}

…where ‘is’ is the InputStream presented above and ‘f’ is a File object where the bytes will be saved.

View the list of posts on Messaging here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

38 Responses to How to post a Multipart http message to a web service in C# and handle it with Java

  1. chintan says:

    how if java service is authenticated by user id and password… where should i put my id and password in .net client.

    • Andras Nemes says:

      Hi Chintan,
      That depends on the authentication type of the service. The most direct approach is to put the username + password in the auth header of the HTTP message from the client: Authorization Basic base64encode(username:password). Let me know if you’re not sure how to do this and I’ll provide a code example.

      A clear drawback with this approach is that if someone’s listening to the traffic between the service and the client then they’ll be able to extract the auth header. If you have access to an X509 certificate then you can tighten the messaging security around the java service with SSL (https://).

      //Andras

  2. chintan says:

    below are some information related java service

    https://testsmartlab.iowaehealth.net/ws/d1/bcdc_elr.jws?WSDL=

    Once you have a copy of the WSDL you can use it as a guide for your own custom web service development or as an input to a SOAP with Attachments (SwA) compliant web service stub generation program like Apache’s wsdl2java (ws.apache.org/axis) or Microsoft Visual Studio.
    While the MIME attachment style is easiest to develop with Java and .NET based SOAP technologies, a pure HTTP Post solution to transmit a message can be implemented in any language. The following overview of an ELR transmission is provided to give insight to those implementing a true SOAP client and those using an HTTP style batch upload. The text provided in the example can be used as a template for creating a HTTP Post.
    The table below provides an example depicting the data contained in the transmission of an ELR batch. The first column contains annotations useful for referring to specific message parts. The annotations would not be seen in an actual message. The message content is contained in the second column. The table itself is only used to organize the information; in an actual transmission, the data in the second column would be seen as one contiguous stream. The majority of the text in the second column is boilerplate. The bold text in the second column is text that would be changed by the reporting entity (more on this to follow).
    The example logically divides the message up into three sections. The first section, represented by the first table row (lines 1-10) contains the HTTP parameters. These parameters are critical to the successful negotiation of the communication between the client and the web service. The only non-standard HTTP parameter is the last (line 10) and is required by the SOAP protocol to successfully route the message to the correct SOAP operation. Reporting entities must change the last portion of the SOAPAction URL to the operation name appropriate for the message batch encoding style being transmitted.
    The Content-Type (line 2) parameter is critical to the correct handling of the message attachment. The first two elements multipart/related; type=”text/xml”; tell the server to expect a message that adheres to the multipart/related protocol and that the message payload will be either text or xml. Multipart/related messages require that each message part contain a Content-Id to uniquely identify the part within the message. The Content-Type start element makes reference to the Content-Id of the first message part. If the value found for start is not associated with any message parts, the message will fail to process. Finally, message parts are delimited using a simple string delimiter. The boundary defines the delimiter.
    The second section in the table contains the SOAP message part. It starts with the boundary delimiter on line 11 and is followed by three parameters that describe the part. The third parameter Content-Id (line14) is the critical unique identifier for the part. Note that the value for Content-Id on line 14 is identical to the value for start in the Content-Type parameter on line 2. This identifies the part as the first in the message.

  3. chintan says:

    able 1 – Example HTTP Post containing a SOAP message
    The SOAP part’s payload (line 15) is a complete XML document. Here again reporting entities will need to modify the operation name to correspond to the message batch encoding style. Note that the tag nested in the operation tag is a reference to the name of a parameter (dh) defined for the operation. Also notice that the parameter element contains no body and only one attribute. The attribute is an href with the value “cid:A0D00719EDA95AB72853A1CA02E11E95” which when read by the server is used as a pointer to the message part that should be provided as the value for the send_rds_batch operation’s dh parameter.
    The last section (lines 16-21) starts with the boundary on line 16 and contains the batch file. Note that its Content-Id matches exactly with the value referenced in the dh element’s href. The batch content starts on line 20 and must follow the formatting rules appropriate to the chosen encoding style (SMF, HL7-EDI, or HL7-XML). The message must be terminated with a boundary (line 21) to signal its end.
    The software that produced the message dynamically generated all the unique identifiers used in the example. If you decide to create your own HTTP style transmission software, you can choose any identifiers you want as long as the reference requirements mentioned above are satisfied. For instance, the first message part could be named “soap_body” and the second message part “batch_file” as long as the start attribute in the Content-Type parameter is set to “soap_body” and the href attribute of the dh element is set to “batch_file.”

  4. Andras Nemes says:

    what are you expecting me to do with all this information and what does it have to do with your original question, i.e. how to send login information to a java web service?

  5. chintan says:

    i have created my .net client but.. i am not able to send successful message

  6. chintan says:

    my code

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Windows.Forms;
    using System.IO;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;
    using Smartlab.BCDC_ELRSoap;

    namespace Smartlab
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

    SendFileToServer(@”C:\Users\chpatel\Desktop\d45699b3a01000000809c10512e5b38_20130805120016.txt”);

    }

    private static void SendFileToServer(string fileFullPath)
    {
    FileInfo fi = new FileInfo(fileFullPath);
    string fileName = fi.Name;
    byte[] fileContents = File.ReadAllBytes(fi.FullName);

    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(@”https://testsmartlab.iowaehealth.net/ws/d1/bcdc_elr.jws?WSDL”));

    requestMessage.Headers.ExpectContinue = false;

    MultipartFormDataContent multiPartContent = new MultipartFormDataContent(“—-MyGreatBoundary”);
    ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
    byteArrayContent.Headers.Add(“Content-Type”, “text/xml; charset=UTF-8”);
    byteArrayContent.Headers.Add(“Content-Transfer-Encoding”, “binary”);
    multiPartContent.Add(byteArrayContent, “d45699b3a01000000809c10512e5b38_20130805120016″, fileName);
    requestMessage.Content = multiPartContent;

    try
    {
    var credCache = new CredentialCache();
    credCache.Add(new Uri(@”https://testsmartlab.iowaehealth.net/ws/d1/bcdc_elr.jws?WSDL”), “Basic”, new NetworkCredential(“d1_ws_submitter”, “idssqa11”));
    var httpClient = new HttpClient(new HttpClientHandler { Credentials = credCache });

    Task httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
    HttpResponseMessage httpResponse = httpRequest.Result;
    HttpStatusCode statusCode = httpResponse.StatusCode;
    HttpContent responseContent = httpResponse.Content;

    if (responseContent != null)
    {
    Task stringContentsTask = responseContent.ReadAsStringAsync();
    String stringContents = stringContentsTask.Result;
    MessageBox.Show(stringContents);
    }

    bcdc_elrSoapClient serviceClient = new bcdc_elrSoapClient();

    serviceClient.ClientCredentials.UserName.UserName = “d1_ws_submitter”;
    serviceClient.ClientCredentials.UserName.Password = “”;

    try
    {
    FileInfo fi1 = new FileInfo(@”C:\Users\Public\3D408EDC5A485D0AEE8CDB3A7105E29D.txt”);
    string fileName1 = fi1.Name;
    byte[] fileContents1 = File.ReadAllBytes(fi1.FullName);
    MessageBox.Show(serviceClient.send_rds_batch(fileContents1));
    }

    catch (Exception exc)
    {
    throw (exc);

    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.Message);
    }
    }
    }
    }

  7. Divya says:

    Hi Andras Nemes ,

    I have a query. I need to pass a multipart response from my web server( a web service) to the client page. This is how I implemented.

    byte[] ImageData = null;
    ImageData = File.ReadAllBytes(“D:\\Tulips.jpg”);
    MultipartFormDataContent multipartContent = new MultipartFormDataContent();
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

    ByteArrayContent fileContent = new ByteArrayContent(ImageData);
    fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(“image/jpeg”);
    fileContent.Headers.ContentLength = ImageData.Length;
    multipartContent.Add(fileContent);

    StringContent body = new StringContent(“xml”);
    body.Headers.ContentType = “xxx-xml”;
    multipartContent.Add(body);

    result.Content = multipartContent;.

    Being new to asp.net and multi-part response concept, is it enough to assign the multipartContent to HttpResponseMessage content. Or do we need to invoke any func like – = httpClient.SendAsync() in the web server part. My requirement is to provide a multi-part response to a web page. I am developing only the web service part not the client page. I just need to provide the response of this format.

    My sample response format is:

    HTTP/1.0 200 OK
    Date: Wed, 03 Mar 2004 14:45:11 GMT
    Server: xxx
    Connection: close
    Content-Type: application/xxx-multipart
    Content-Length: 6851

    Content-Type: image/jpeg
    Content-Length: 5123
    CommandID: asset14521

    Content-Type: xxx-xml
    Content-Length: 1523

    ?<xml…

    Will I achieve the above response format using my code implemented below. Please help

    Thanks,
    Divya

    • Andras Nemes says:

      Divya,
      you don’t need to call SendAsync in the response from the web server to the client. If you have a Web API REST service then just return a HttpResponse message. Default GET signature:

      public HttpResponseMessage Get()
      {
             //do some work here
             HttpResponseMessage responseMessage 
      }
      

      Then you wrap the message content in the HttpResponseMessage object within the function body, like you suggested in your sample code:

      HttpResponseMessage message = new HttpResponseMessage(some status code);
      MultipartContent mc = new MultipartContent("subtype", "boundary");
      mc.Add(some http content, such as ByteArrayContent or StringContent);
      

      …finally return the HttpResponseMessage object using the built-in reference to the original HttpRequestMessage:

      HttpResponseMessage message = new HttpResponseMessage(some status code);
      MultipartContent mc = new MultipartContent("subtype", "boundary");
      return Request.CreateResponse<T>(statusCode, instance of T);
      

      //Andras

      • Divya says:

        Hi Andras,

        Thanks for the response. I would like to know in case of Get method, how will we access this function in the client side. Its just for my awareness.

        Also, do we have any other alternative method rather that implementing this code in GET signature. I just want to know if there is any other implementation method.

        Thanks,
        Divya

      • Andras Nemes says:

        Hi Divya,

        The client simply sends a GET request to the appropriate URL. If you have a CustomersController with a Get() method then it can be reached with GET [base uri]/Customers.

        Yes, you can name the Get method as you wish and decorate the method with the [Get] attribute.

        I recommend that you go through the following:

        Web API intro:
        http://www.asp.net/web-api

        How to make HTTP calls with HttpClient:
        http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx

        //Andras

      • Divya says:

        Hi Andras,

        Missed to include my main query in my below post. My web service is exposing a func -ex : DownloadResponse() which serves the functionality of returning the multi-part response. So if I go for Get() signature implementation, how can I use this function?

      • Andras Nemes says:

        …use the [Get] attribute to decorate the DownloadResponse method.
        Go through the Web API intro that I referred to in my previous response. You’ll understand much more.
        //Andras

      • Divya says:

        Hi Andras,

        Our HTTP request and response messaging should be carried out using HTTP POST method. I implemented as below.

        _
        _
        _
        Public Function DownloadImages(ByVal downloadImageRequest As String) As HttpResponseMessage
        {
        .
        .
        .}

        But while referring this web service in a sample test web client, am getting the below error –
        Server Error in ‘/’ Application.
        ——————————————————————————–

        To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy. System.Net.Http.Headers.HttpContentHeaders does not implement Add(System.Object).

        Please suggest.

  8. Divya says:

    Hi Andras,

    I read in one of the article that we cannot use HTTPResponseMessage as it is not serializable. I believe I am getting the below mentioned error as am returning HTTPResponseMessage from a function decorated with WebMethod attribute. Is there any alternate solution./ remedy to resolve the same.

    Error:
    Server Error in ‘/’ Application.
    ——————————————————————————–

    To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy. System.Net.Http.Headers.HttpContentHeaders does not implement Add(System.Object).

    My function:

    [httppost]
    [Actionname()]
    [WebMethod]
    _
    Public Function DownloadImages(ByVal downloadImageRequest As String) As HttpContent
    {
    // code
    }

    • Andras Nemes says:

      Divya, why WebMethod? I return HttpResponseMessage from every single Web API method I have in my projects, examples:

      public async Task<HttpResponseMessage> Get()
      public async Task<HttpResponseMessage> Post(int customerId, SelfServiceFileSaveViewModel viewModel)
      public async Task<HttpResponseMessage> Get(int customerId, int fileId)
      

      However, you can return any type of object from these web api methods, even plain strings. If web api has difficulties serialising your objects as XML then why not switch to JSON? In WebApiConfig.Register(HttpConfiguration config) you can register the JSON formatter available in JSON.NET (Newtonsoft):

      var json = config.Formatters.JsonFormatter;
      json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
      config.Formatters.Remove(config.Formatters.XmlFormatter);
      

      //Andras

      • Divya says:

        Andras, I believe I need to have VS 2012 or later to get support for Task, async, await keywords. I am using Visual Studio 2010. Moreover, my project is normal asp.net web service and not an mvc web service containing controllers.

        How can i access this function without including WebMethod attirbute

        [httppost]
        [Actionname()]
        _
        Public Function DownloadImages(ByVal downloadImageRequest As String) As HttpContent
        {
        // code
        }

      • Andras Nemes says:

        Divya, ok, I thought you had access to later technologies. Now I see that you’re not using the Web API platform, but an old way of creating asp.net web services. Is it .asmx files you’re working with? Even WCF would be better than that, although it is getting out of fashion quickly nowadays.
        In this case all I’ve told you about the Web API related objects, such the HttpResponseMessage, is irrelevant.
        To be honest I’ve long forgotten how to create and use asmx web services so I’m out of ideas. You’ll for sure need the [WebMethod] attribute, but I really don’t know how routing works, i.e. how to route a request to DownloadImages, possibly …/DownloadImages.asmx.
        You’re better off asking on StackOverflow if you’re stuck.
        //Andras

  9. Divya says:

    Hi Andras,

    I tried my requirement with VS 2010 -, MV3 web application. I developed a controller with function as

    Public Function PostDownloadImageRequest() As HttpResponseMessage
    {
    }

    For testing purpose when i accessed this using http:\\localhost:50611\ControllerName\Download, soem HTTPResponseMessage was getting print with status ok.
    My queries related to this implementations are:
    a) My understanding is we need to use HttpPost attribute only when the method to be invoked for POST method doesn’t begins with Post. IS that right?
    b) In this new mvc project, we dont have to refer the web service in our client application like our old web services using asmx.. SO in such a case, how can a button click would handle this?
    c) How to host this service. Is there any link that is simple and helpful for beginners like me.

    Thanks

    • Andras Nemes says:

      Divya, I’m not sure I’m with you. The original post is about web services but now you’re asking about a web project with MVC and how to handle button clicks. I definitely cannot provide an MVC tutorial in a comment field like this. If you’re new to MVC then go through the tutorials here: http://www.asp.net/mvc/tutorials/mvc-4. I suggest that you start with MVC4 as MVC3 is getting really outdated now that MVC5 is available. I think MVC4 can be run in VS2010 but you might need to download the project type from MS.
      //Andras

  10. abhishek says:

    how to delete that file after uploading.

    error is comes its us e by othe porcess

    • Andras Nemes says:

      Have you released all handles with close()? Example:

      byte[] decodedBytes = //file bytes
      String fileContents = new String(decodedBytes, java.nio.charset.StandardCharsets.UTF_8);
      File f = new File(full file path);
      FileOutputStream fileOutputStream = new FileOutputStream(f);
      FileChannel fileChannel = fileOutputStream.getChannel();
      BufferedWriter bf = new BufferedWriter(Channels.newWriter(fileChannel, "UTF-8"));
      bf.write(fileContents);
      bf.close();
      fileChannel.close();
      
      
      //delete file
      f.delete();
      
  11. chintan says:

    help me!!!

  12. The Bala says:

    how to handle this multipart/form-data message in php?

  13. The Bala says:

    can i upload image using this same code? if yes, which one contains image byte data? here you have attached two things are btyeArrayContent and fileName. which on holds image byte data? thanks for your help

    • Andras Nemes says:

      It’s the byte array content that holds the bytes you want to upload, whether it’s an image or text file.
      //Andras

      • The Bala says:

        ok dear brother. no doubts with your code. i understood well, and great job you have dob\ne for us. pls say me which variable you have used here to holds byte data . because that variable is used in php to receive the data

      • Andras Nemes says:

        This bit of code definitely sets up the byte array that you want to send to the web service:

        MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----MyGreatBoundary");
        ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
        byteArrayContent.Headers.Add("Content-Type", "application/octet-stream");
        multiPartContent.Add(byteArrayContent, "this is the name of the content", fileName);
        requestMessage.Content = multiPartContent;
        

        The receiving part is shown further down in the post, although it’s in Java.
        //Andras

  14. The Bala says:

    my biggest doubt is can i upload upto 10MB picture?please clear me. actually i am android c\developer currently working in xamarin.ios . so i am new to c#. thats y i am asking this type of questions.

    • Andras Nemes says:

      if there’s a limitation then you’ll most likely find it in the infrastructure, not in code. 10MB is not too large, it’s 10485760 bytes, that’s not even close to limits like Int.Max.

      E.g. there’s a maximum load you can set on IIS, I guess there’s something similar for Android apps.
      //Andras

  15. The Bala says:

    okay Andras Nemes. thank you

  16. The Bala says:

    Thank you mr.adras nems.. i solve my problem.. your coding helped me in such a great way

  17. tommy2013 says:

    Nice post. I was checking constantly this blog and
    I am impressed! Very helpful information particularly the last part 🙂 I care for such info a lot.
    I was seeking this certain info for a very long time.
    Thank you and good luck.

  18. Hi Andras
    I need to write a client which upload a document in using REST Web Serice. This server need to receive a parameter which includes “FormDataBodyPart” this is a method belonging to “BodyPart” java lib.
    The problem is that I do not find any equivalent method in .Net.
    I am able to upload the file but, without using FormDataBodyPart, the server is not able to get the”Original File Name” and the “mime type”.

    The server documentation suggest to use the following call:
    FormDataBodyPart bodyPart = new FormDataBodyPart(“file”,
    new ByteArrayInputStream(BYTEARRAY),
    MediaType.APPLICATION_OCTET_STREAM_TYPE);

    As I told you I have not be able to find how tot replicate this object in .,Net.
    Do you have any idea about?
    Thank a lot
    Lucio

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Ricos Blog zu Softwaredesign- und architektur

Ideen und Gedanken rund um Softwaredesign und -architektur, Domain-Driven Design, C# und Windows Azure

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: