1/** 2 * 上传文件 3 * 4 * @param uploadUrl 5 * 上传地址 6 * @param param 7 * 参数 8 * @param filepath 9 * 文件路径 10 * @return 结果 11 */ 12 public static String upload(String uploadUrl, HashMap<String, String> param, String fieldName, String filepath) { 13 StringBuilder result = null; 14 try { 15 String boundary = "---------------------------esa000000000001"; 16 URL url = new URL(uploadUrl); 17 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 18 connection.setDoOutput(true); 19 connection.setDoInput(true); 20 connection.setUseCaches(false); 21 connection.setConnectTimeout(1000 * 20); 22 connection.setReadTimeout(1000 * 20); 23 connection.setRequestMethod("POST"); 24 connection.setRequestProperty("Connection", "Keep-Alive"); 25 connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 26 connection.setRequestProperty("Charsert", "UTF-8"); 27 28 File file = new File(filepath); 29 StringBuilder sbf = new StringBuilder(); 30 sbf.append("--" + boundary + "\r\n"); 31 sbf.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + file.getName() + "\"\r\n"); 32 sbf.append("Content-Type: application/octet-stream" + "\r\n\r\n"); 33 byte[] fz = sbf.toString().getBytes(); 34 StringBuilder sb = new StringBuilder(); 35 sb.append("\r\n\r\n"); 36 Iterator<String> iterator = param.keySet().iterator(); 37 while (iterator.hasNext()) { 38 String key = iterator.next(); 39 String value = param.get(key); 40 sb.append("--" + boundary + "\r\n"); 41 sb.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n"); 42 sb.append("\r\n"); 43 sb.append(value + "\r\n"); 44 } 45 byte[] before = sb.toString().getBytes(); 46 byte[] after = ("\r\n--" + boundary + "--\r\n").getBytes(); 47 connection.setRequestProperty("content-length", (before.length + fz.length + file.length() + after.length) + ""); 48 DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); 49 dos.write(fz); 50 FileInputStream fis = new FileInputStream(file); 51 byte[] buffer = new byte[1024 * 10]; 52 int len; 53 while ((len = fis.read(buffer)) != -1) { 54 dos.write(buffer, 0, len); 55 } 56 dos.write(before); 57 dos.write(after); 58 dos.flush(); 59 int code = connection.getResponseCode(); 60 InputStream stream = connection.getInputStream(); 61 byte[] b = new byte[1024 * 10]; 62 int l; 63 result = new StringBuilder(); 64 while ((l = stream.read(b)) != -1) { 65 result.append(new String(b, 0, l, "utf-8")); 66 } 67 fis.close(); 68 dos.close(); 69 stream.close(); 70 } catch (MalformedURLException e) { 71 } catch (ProtocolException e) { 72 } catch (IOException e) { 73 } finally { 74 75 } 76 if (result == null) { 77 return null; 78 } else { 79 return result.toString(); 80 } 81 }
Android文件上传
Stella981
2021-10-11
1435 0 0
点赞
收藏
评论区
加载中...