title: How to send local .png to .php file on server using java application?
body: <p>I have a local .png file that I want to send using POST data to a .php script that will save the data to a .png file on the server. How do I do this? Do I have to encode or something? All I have is a File and a way to POST data.</p>
  
  <p>Here is how I am sending the .png:</p>
  
  <pre><code>public static byte[] imageToByte(File file) throws FileNotFoundException {
      FileInputStream fis = new FileInputStream(file);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] buf = new byte[1024];
      try {
          for (int readNum; (readNum = fis.read(buf)) != -1;) {
              bos.write(buf, 0, readNum);
          }
      } catch (IOException ex) {
      }
      byte[] bytes = bos.toByteArray();
      return bytes;
  }
  
  public static void sendPostData(String url, HashMap&lt;String, String&gt; data)
          throws Exception {
      URL siteUrl = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setDoInput(true);
  
      DataOutputStream out = new DataOutputStream(conn.getOutputStream());
  
      Set keys = data.keySet();
      Iterator keyIter = keys.iterator();
      String content = "";
      for (int i = 0; keyIter.hasNext(); i++) {
          Object key = keyIter.next();
          if (i != 0) {
              content += "&amp;";
          }
          content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
      }
      System.out.println(content);
      out.writeBytes(content);
      out.flush();
      out.close();
      BufferedReader in = new BufferedReader(new InputStreamReader(
              conn.getInputStream()));
      String line = "";
      while ((line = in.readLine()) != null) {
          System.out.println(line);
      }
      in.close();
  }
  </code></pre>
  
  <p>The PHP script:</p>
  
  <pre><code>&lt;? 
  // Config
  $uploadBase = "../screenshots/";
  $uploadFilename = $_GET['user'] . ".png";
  $uploadPath = $uploadBase . $uploadFilename;
  
  // Upload directory
  if(!is_dir($uploadBase))
  mkdir($uploadBase);
  
  // Grab the data
  $incomingData = $_POST['img'];
  
  // Valid data?
  if(!$incomingData || !isset($_POST['img']))
  die("No input data");
  
  // Write to disk
  $fh = fopen($uploadPath, 'w') or die("Error opening file");
  fwrite($fh, $incomingData) or die("Error writing to file");
  fclose($fh) or die("Error closing file");
  
  echo "Success";
   ?&gt;
  </code></pre>