【发布时间】:2012-01-18 01:25:28
【问题描述】:
我的代码:
public static String newName =""; //the traditional Chinese file name
public static String uploadFile =""; //the file path contain traditional Chinese
public static String ActionUrl =""; //the server
public static void upload() {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL url = new URL(ActionUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Accept", "text/*");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data;" + "name=\"folder\"" + end + end + "/mnt/HD/HD_a2/test/" + end);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data;" + "name=\"Filedata\"; filename=\"" + newName + "\"" + end);
ds.writeBytes(end);
FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
fStream.close();
ds.flush();
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while((ch = is.read()) != -1) {
b.append((char)ch);
}
System.out.println("UPLOAD" + "SUCCESS");
ds.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
上传文件成功,但文件名乱码。 如何修改?
【问题讨论】:
-
文件名没有以预期的字符集(可能是 UTF-8)提供,或者接收服务器不知道如何处理该字符集中的传入数据。您可能想在发送文件名时尝试使用 writeUTF 而不是 writeBytes,但这本身可能是一个问题,因为它不会以这种方式编写真正的 UTF-8,而是modified UTF-8 - 并且在某些情况下修改后的 UTF-8 与真正的 UTF-8 不同,服务器可能会抱怨。
-
为什么要使用 DataOutputStream?为什么你认为它通过 writeBytes 处理中文文本是正确的?
-
我尝试用 writeUTF 替换所有 writeBytes。但是没有显示错误信息,也没有上传成功。
-
@brian:那么问题可能出在服务器上(也许它不需要 UTF-8),或者代码中可能还有其他问题。除非您提供更多详细信息(最好是发出的确切 HTTP 请求;为此使用网络或 HTTP 嗅探器),否则我们无法轻易判断。理想情况下,您还应该检查如果您尝试使用浏览器会发生什么;如果它不起作用,那么很可能是服务器;如果它确实以这种方式工作,那么比较 HTTP 请求以查看它们的不同之处 - 这将告诉您 哪里 问题出在哪里,然后您可以尝试专门修复它。
-
我尝试使用浏览器上传带有中文文件名的文件。它成功了。我使用wireshark来监控数据包。文件名部分相同。但是我的java客户端不工作,浏览器客户端工作。