title: C# & Java - Uploading a file from Android to WCF
body: <p>I'm trying to upload a file from Android to a WCF Service.
  I've gotten to the point where the method on the WCF is triggered and the file saves. 
  When trying to open the file, I get an error message stating that it's been corrupted.</p>
  
  <p>I think the error might be in the HttpFileUpload class that one of the static variables are incorrect or that what I'm sending up isn't a stream but instead something else that the service converted to a stream somehow thus the corruption.</p>
  
  <p>The code used can be found below.</p>
  
  <p>Android Code:</p>
  
  <p>HttpFileUpload Class:</p>
  
  <p>The HttpFileUpload code found <a href="http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically" rel="nofollow">here</a>:</p>
  
  <pre><code>private static final String LINE_FEED = "\r\n";
  private String charset = "UTF-8";
  
  public HttpFileUpload(String requestURL) throws IOException {
  
      // creates a unique boundary based on time stamp
      boundary = "===" + System.currentTimeMillis() + "===";
  
      URL url = new URL(requestURL);
      httpConn = (HttpURLConnection) url.openConnection();
      httpConn.setUseCaches(false);
      httpConn.setDoOutput(true); // indicates POST method
      httpConn.setDoInput(true);
      httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
      httpConn.setRequestProperty("Host", "x.x.x.x:x");
      outputStream = httpConn.getOutputStream();
      writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
  }
  
  public void addFilePart(String fieldName, File uploadFile) throws IOException {
      String fileName = uploadFile.getName();
      writer.append("--" + boundary).append(LINE_FEED);
      writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED); // form-data
      writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
      writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
      writer.append(LINE_FEED);
      writer.flush();
  
      FileInputStream inputStream = new FileInputStream(uploadFile);
      byte[] buffer = new byte[4096];
      int bytesRead = -1;
      while ((bytesRead = inputStream.read(buffer)) != -1) {
          outputStream.write(buffer, 0, bytesRead);
      }
      outputStream.flush();
      inputStream.close();
  
      writer.append(LINE_FEED);
      writer.flush();
  }
  
  public List&lt;String&gt; finish() throws IOException {
      List&lt;String&gt; response = new ArrayList&lt;String&gt;();
  
      writer.append(LINE_FEED).flush();
      writer.append("--" + boundary + "--").append(LINE_FEED);
      writer.close();
  
      int status = httpConn.getResponseCode();
      if (status == HttpURLConnection.HTTP_OK) {
          BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
          String line = null;
          while ((line = reader.readLine()) != null) {
              response.add(line);
          }
          reader.close();
          httpConn.disconnect();
      } else {
          throw new IOException("Server returned status: " + status);
      }
  
      return response;
  }
  </code></pre>
  
  <p>Service Connector Class</p>
  
  <pre><code>    String urlTo = LOCATION + "/UploadUserProfilePicture";
      File file = new File(imagePath);
  
      try {
          HttpFileUpload httpFileUpload = new HttpFileUpload(urlTo);
  
          httpFileUpload.addFilePart("image", file);
  
          List&lt;String&gt; responses = httpFileUpload.finish();
  
          for (String line : responses) {
              System.out.println(line);
          }
  
          return responses.get(0);
  
      } catch (Exception ex) {
          return ex.toString();
      }
  </code></pre>
  
  <p>WCF Service Code</p>
  
  <p>IMobileService:</p>
  
  <pre><code>    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
      [OperationContract]
      Result UploadUserProfilePicture(Stream image);
  </code></pre>
  
  <p>MobileService:</p>
  
  <p>The <code>FileType fileType = bytes.GetFileType()</code> is a plugin that returns the extension. Currently the plugin does not work as the fileType is always null.
  However the image variable might already be corrupted.</p>
  
  <pre><code>public Result UploadUserProfilePicture(Stream image)
      {
          try
          {
              var bytes = CommonMethods.ReadToEnd(image);
              FileType fileType = bytes.GetFileType();
  
              Guid guid = Guid.NewGuid();
              string imageName = guid.ToString() + "." + fileType.Extension;
              var buf = new byte[1024];
              var path = Path.Combine(@"C:\fileUpload\" + imageName); //" ocd
  
              File.WriteAllBytes(path, bytes);
  
              return new Result
              {
                  Success = true,
                  Message = imageName
              };
          }
          catch(Exception ex)
          {
              return new Result
              {
                  Success = false,
                  Message = ex.ToString()
              };
          }
      }
  </code></pre>