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(); } }
相关文章推荐
- android 多个cursor 的读取 和读取某个Cursor其他从集合中获取的速度比较
- Android导入项目时Android jar包丢失的解决
- Android MVC模式的原理
- android:gravity和android:layout_gravity的区别
- android 启用硬件加速
- 中国移动苏杭研发中心---android应用开发
- 中国移动苏杭研发中心---android应用开发
- AndroidAnnotations 3.0 更新说明
- Android Jni 用动态库的加载与卸载函数说明
- Android之判断某个服务是否正在运行的方法
- Android之判断某个服务是否正在运行的方法
- Android task介绍
- Android 查看内存使用情况
- Android TextView设置部分文字样式
- android_AsyncTask与Handler的相同点跟区别
- android开发的环境配置
- MeasureSpec介绍
- Android的数据存储方式
- android 开源项目整理
- android_AsyncTask的用法总结