您的位置:首页 > 移动开发 > Android开发

Android文件上传,关键代码

2014-01-09 15:15 330 查看
private void upload(String srcPath, String uploadPath) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try {
URL url = new URL(uploadPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

// 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃
// 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
conn.setChunkedStreamingMode(128 * 1024);// 128K
// 允许输入输出流
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);

// 使用POST方法
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);

DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
+ "\""
+ end);
dos.writeBytes(end);

FileInputStream fis = new FileInputStream(srcPath);
byte[] buffer = new byte[8192]; // 8k
int len = 0;
// 读取文件
while ((len = fis.read(buffer)) != -1) {
dos.write(buffer, 0, len);
}
fis.close();

dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
dos.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: