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 }
Android客户端上传文件到服务器端
Stella981
2021-10-11
1121 0 0
点赞
收藏
评论区
加载中...