Java/PNG upload to .php

痴心易碎 提交于 2019-12-25 01:26:05

问题


This is what the local .png file has when I edit it w/ notepad:

http://i.stack.imgur.com/TjNGl.png

This is what the uploaded .png file has when I edit it w/ notepad:

http://i.stack.imgur.com/2tXgN.png

Why is 'NUL' being replaced with '\0'? This makes the file corrupt and unusable.

I use this java code to upload the local .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();
}

回答1:


I am just guessing here

But I think thats how URLEncoder works.. it doesn't decode the proper character bytes. Check this out http://www.w3schools.com/tags/ref_urlencode.asp

NUL null character %00

If you have access to your site php.. I recommend posting a encoded base64 representation of the png data.. to PHP.. then decoding the base64 on php side.. it will be 100% accurate then. As all of base64 characters are accepted in URLEncoding.

Or if you are super lazy and still want to use UrlEncoder you can replace every NUL back with byte 0, which will yeah add a lot of extra processing for no reason.

But then again you can always upload data using multipart/form-data as that requires alot more work..

I'd recommand a quick fix for now try the base64 encoding trick.



来源:https://stackoverflow.com/questions/6932058/java-png-upload-to-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!