Android客户端上传文件到服务器端

1/** 2 * 上传文件 3 */ 4 public static String sendFile(String urlPath, String filePath, 5 String newName) throws Exception { 6 String end = "\r\n"; 7 String twoHyphens = "--"; 8 String boundary = "*****"; 9 10 URL url = new URL(urlPath); 11 HttpURLConnection con = (HttpURLConnection) url.openConnection(); 12 /* 允许Input、Output,不使用Cache */ 13 con.setDoInput(true); 14 con.setDoOutput(true); 15 con.setUseCaches(false); 16 /* 设置传送的method=POST */ 17 con.setRequestMethod("POST"); 18 /* setRequestProperty */ 19 20 con.setRequestProperty("Connection", "Keep-Alive"); 21 con.setRequestProperty("Charset", "UTF-8"); 22 con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" 23 + boundary); 24 /* 设置DataOutputStream */ 25 DataOutputStream ds = new DataOutputStream(con.getOutputStream()); 26 ds.writeBytes(twoHyphens + boundary + end); 27 ds.writeBytes("Content-Disposition: form-data; " 28 + "name=\"file1\";filename=\"" + newName + "\"" + end); 29 ds.writeBytes(end); 30 31 /* 取得文件的FileInputStream */ 32 FileInputStream fStream = new FileInputStream(filePath); 33 /* 设置每次写入1024bytes */ 34 int bufferSize = 1024; 35 byte[] buffer = new byte[bufferSize]; 36 37 int length = -1; 38 /* 从文件读取数据至缓冲区 */ 39 while ((length = fStream.read(buffer)) != -1) { 40 /* 将资料写入DataOutputStream中 */ 41 ds.write(buffer, 0, length); 42 } 43 ds.writeBytes(end); 44 ds.writeBytes(twoHyphens + boundary + twoHyphens + end); 45 46 /* close streams */ 47 fStream.close(); 48 ds.flush(); 49 50 /* 取得Response内容 */ 51 InputStream is = con.getInputStream(); 52 int ch; 53 StringBuffer b = new StringBuffer(); 54 while ((ch = is.read()) != -1) { 55 b.append((char) ch); 56 } 57 /* 关闭DataOutputStream */ 58 ds.close(); 59 return b.toString(); 60 }

原帖地址:http://blog.csdn.net/lk\_blog/article/details/7706348

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )