java模拟浏览器上传文件
2016-02-29 14:36
381 查看
public static void main(String[] args) { String str = uploadFile("C:/Users/RGKY/Desktop/wKgBHVbLtuWAVNZAAABB_J2qzhc553.jpg", "http://localhost:8087/worldapp/fastfds/uploadSingleFile.cf?fieldName=selectFile", "wKgBHVbLtuWAVNZAAABB_J2qzhc553.jpg"); System.out.println(str); } /** * * @param file * 待上传的文件路径 * @param uploadUrl * 上传服务接口路径 * @param fileName * 文件名称,服务器获取的文件名称 * @return */ public static String uploadFile(/* Bitmap src */String file, String uploadUrl, String fileName) { String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃 // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。 httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K // 允许输入输出流 httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); // 使用POST方法 httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); // name相当于html标签file的name属性,fileName相当于标签value值 dos.writeBytes("Content-Disposition: form-data;name=\"selectFile\";fileName=\"" + fileName + "\"" + end); dos.writeBytes(end); // 将要上传的内容写入流中 // InputStream srcis = Function.Bitmap2IS(src); InputStream srcis = new FileInputStream(file); byte[] buffer = new byte[8192]; // 8k int count = 0; // 读取文件 while ((count = srcis.read(buffer)) != -1) { dos.write(buffer, 0, count); } srcis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); // 上传返回值 String sl; String result = ""; while ((sl = br.readLine()) != null) result = result + sl; br.close(); is.close(); return result; } catch (Exception e) { e.printStackTrace(); return "网络出错!"; } }
相关文章推荐
- 如何在eclipse中看到java基础类的源代码
- SpringMVC中使用Interceptor拦截器
- Struts2学习(一) 基础环境搭建与创建HelloWorld程序
- Java关键字static、final使用小结
- springMVC+Java验证码完善注册功能
- java中javamail收发邮件实现方法
- java里int和Integer什么区别
- java JDK8 学习笔记——助教学习博客汇总
- Java 设计模式之观察者模式
- 关于java以竖线作为分隔符split字符串的问题
- 开源 免费 java CMS - FreeCMS2.0 会员我的评论
- (一)JavaMail 简介
- java集合框架小结
- java利用snmp4j包来读取snmp协议数据
- JAVASE eclipse中的命名
- Java编程基础----Java中有哪些数据类型?
- 开源项目导入eclipse的一般步骤
- Java线程池源码分析(二)
- 深入理解Java中static关键字的使用
- Java八种基本数据类型的比较及其相互转化