0

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.

Here is how I am sending the .png:

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<String, String> 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 += "&";
        }
        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();
}

The PHP script:

<? 
// 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";
 ?>
Sam
  • 171
  • 1
  • 2
  • 8
  • When I try to upload, the image is corrupt. When I open the .png with notepad, I see that everything is the same as the local file except there are '\0's instead of 'NUL's – Sam Aug 03 '11 at 18:10
  • Show your code. Are you doing a simple post or a form-encoded post? – Michael-O Aug 03 '11 at 18:33
  • I edited the main post w/ the methods. – Sam Aug 03 '11 at 18:52
  • Where the PHP code? This might be the problem. Have a look at [this](http://stackoverflow.com/q/1314249/696632). – Michael-O Aug 03 '11 at 19:28
  • I just edited w/ the PHP code. I looked at that link and tried using file_get_contents('php://input') but what the java is sending as post data doesn't match what's in the actual .png. does it have to be encoded or decoded? – Sam Aug 03 '11 at 19:39
  • Both Java and PHP code won't work. You have POSTing parameters in the post body. At no point any file is uploaded actually. You have to retrieve your data with `$body = file_get_contents('php://input');` and write this to a file. You cannot parse the body with $_POST because it contains the binary of the image. – Michael-O Aug 03 '11 at 19:48

2 Answers2

0

My minimalistic code works:

$body = file_get_contents('php://input');
$fh = fopen('file.txt', 'w') or die("Error opening fil
e");
fwrite($fh, $body) or die("Error writing to file");
fclose($fh)

curl --upload-file download.txt http://example.com/upload.php

However, set the method to PUT.

Michael-O
  • 18,123
  • 6
  • 55
  • 121
  • What does the last line do? And I think the problem is in the java or php encoding/decoding because: http://stackoverflow.com/questions/6932058/java-png-upload-to-php – Sam Aug 03 '11 at 20:14
  • The last line sends the file to the PHP script. You Java **and** PHP code is definitively *broken*. – Michael-O Aug 04 '11 at 06:13
0

I must admit, I am surprised that you almost get the correct file. Actually, when you send a file using a browser, the form tag has an encoding defined: enctype="multipart/form-data". I don´t know how it works (It is defined in https://www.rfc-editor.org/rfc/rfc2388), but it includes encoding the file (for example, in Base64). Anyhow, you can forget about the internals if you use a http client library like the one from Apache HttpComponents

Community
  • 1
  • 1
AdrianRM
  • 2,622
  • 2
  • 25
  • 42