问题描述
这是我使用记事本编辑时本地.png文件的内容:
This is what the local .png file has when I edit it w/ notepad:
http://i.stack.imgur.com/TjNGl.png
这是我使用记事本编辑后上传的.png文件的内容:
This is what the uploaded .png file has when I edit it w/ notepad:
http://i.stack.imgur.com/2tXgN.png
为什么将'NUL'替换为'\ 0'?这会使文件损坏且无法使用.
Why is 'NUL' being replaced with '\0'? This makes the file corrupt and unusable.
我使用此Java代码上传本地.png:
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();
}
推荐答案
我只是在这里猜测
但是我认为URLEncoder的工作方式..它无法解码正确的字符字节.看一下这个 http://www.w3schools.com/tags/ref_urlencode.asp
But I think thats how URLEncoder works.. it doesn't decode the proper character bytes.Check this outhttp://www.w3schools.com/tags/ref_urlencode.asp
NUL null character %00
如果您有权访问站点php ..我建议将png数据的编码base64表示形式发布到PHP ..然后在php端解码base64 ..那么它将是100%准确的.由于URLEncoding接受所有base64字符.
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.
或者,如果您超级懒惰并且仍然想使用UrlEncoder,则可以将每个NUL替换为字节0,这是毫无理由的增加了很多额外的处理.
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.
但是您仍然可以始终使用multipart/form-data
上载数据,因为这需要做更多的工作.
But then again you can always upload data using multipart/form-data
as that requires alot more work..
我建议您快速修复一下,现在尝试使用base64编码技巧.
I'd recommand a quick fix for now try the base64 encoding trick.
这篇关于Java/PNG上传到.php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!