具体情况是,我用post上传一个文件,同时还附带一些参数。参数里面有这个即将要上传的文件的生成名。
如果这个生成名的我有encode , 最后在服务器端看到的文件名是encode之后的,服务器端没有帮我decode
如果我不encode,直接在服务器端看到是null或者乱码。
PS: 我还有段只是post参数不post文件的代码,我也有encode,结果服务器端显示是正常的,我得下来也是正常的 并且不用decode。
请问该如何解决?
public static String postFile(String actionUrl, Map<String, String> params, String filePath,
String encoding) {
String newName = "";
if (params.get("type").equals("1")) {
newName = "image.jpg";
} else if (params.get("type").equals("2")) {
newName = "video.mp4";
} else {
newName = "image.jpg";
}
// String uploadFile = "/sdcard/image.JPG";
String LINEND = "\r\n";
String PREFIX = "--";
String BOUNDARY = "*****";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = encoding;
try {
URL url = new URL(actionUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// con.setReadTimeout(DEF.TIMEOUT_POST_CONNECTION);
// con.setConnectTimeout(timeout)
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("connection", "keep-alive");
con.setRequestProperty("Charset", CHARSET);
con.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
// sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(URLEncoder.encode(entry.getValue(), encoding));
sb.append(LINEND);
} DataOutputStream outStream = new DataOutputStream(con.getOutputStream());
outStream.writeBytes(sb.toString());
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + newName + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.writeBytes(sb1.toString()); FileInputStream fStream = new FileInputStream(filePath);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
outStream.write(buffer, 0, length);
}
fStream.close();
outStream.writeBytes(LINEND);
outStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINEND);
outStream.flush();
outStream.close();
String response = read(con.getInputStream());
con.disconnect();
return response;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}