public class HttpManager {
private static final String TAG = "HttpManager";
private static final String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";
/**
*
* @param uploadFile
* 需要上传的文件名
* @param newFileName
* 上传的文件名称,不填写将为uploadFile的名称
* @param urlStr
* 上传的服务器的路径
* @throws IOException
*/
public static String uploadForm(File uploadFile, String newFileName, String urlStr) throws IOException {
String fileFormName = "log_file";
if (newFileName == null || newFileName.trim().equals("")) {
newFileName = uploadFile.getName();
}
StringBuilder sb = new StringBuilder();
/* *//**
* 普通的表单数据
*//*
* for (String key : params.keySet()) { sb.append("--" +
* BOUNDARY + "\r\n"); sb.append(
* "Content-Disposition: form-data; name=\"" + key +
* "\"" + "\r\n"); sb.append("\r\n");
* sb.append(params.get(key) + "\r\n"); }
*/
/**
* 上传文件的头
*/
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"" + fileFormName + "\"; filename=\"" + newFileName + "\""
+ "\r\n");
sb.append("Content-Type: text/html" + "\r\n");// 如果服务器端有文件类型的校验,必须明确指定ContentType
sb.append("\r\n");
byte[] headerInfo = sb.toString().getBytes("UTF-8");
byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("Content-Length",
String.valueOf(headerInfo.length + uploadFile.length() + endInfo.length));
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
InputStream in = new FileInputStream(uploadFile);
out.write(headerInfo);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1)
out.write(buf, 0, len);
out.write(endInfo);
in.close();
out.close();
if (conn.getResponseCode() == 200) {
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] bs = new byte[1024];
int len1 = 0;
while ((len1 = inputStream.read(bs)) != -1) {
stream.write(bs, 0, len1);
}
String string = new String(stream.toByteArray());
LogHelper.d(TAG, "返回值:" + string);
return string;
}
return null;
}
}
Android单文件上传到服务器
最新推荐文章于 2016-11-09 16:58:59 发布