Android文件上传
16lz
2021-01-23
/** * 上传文件 * * @param uploadUrl * 上传地址 * @param param * 参数 * @param filepath * 文件路径 * @return 结果 */public static String upload(String uploadUrl, HashMap<String, String> param, String fieldName, String filepath) {StringBuilder result = null;try {String boundary = "---------------------------esa000000000001";URL url = new URL(uploadUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setUseCaches(false);connection.setConnectTimeout(1000 * 20);connection.setReadTimeout(1000 * 20);connection.setRequestMethod("POST");connection.setRequestProperty("Connection", "Keep-Alive");connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);connection.setRequestProperty("Charsert", "UTF-8");File file = new File(filepath);StringBuilder sbf = new StringBuilder();sbf.append("--" + boundary + "\r\n");sbf.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + file.getName() + "\"\r\n");sbf.append("Content-Type: application/octet-stream" + "\r\n\r\n");byte[] fz = sbf.toString().getBytes();StringBuilder sb = new StringBuilder();sb.append("\r\n\r\n");Iterator<String> iterator = param.keySet().iterator();while (iterator.hasNext()) {String key = iterator.next();String value = param.get(key);sb.append("--" + boundary + "\r\n");sb.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n");sb.append("\r\n");sb.append(value + "\r\n");}byte[] before = sb.toString().getBytes();byte[] after = ("\r\n--" + boundary + "--\r\n").getBytes();connection.setRequestProperty("content-length", (before.length + fz.length + file.length() + after.length) + "");DataOutputStream dos = new DataOutputStream(connection.getOutputStream());dos.write(fz);FileInputStream fis = new FileInputStream(file);byte[] buffer = new byte[1024 * 10];int len;while ((len = fis.read(buffer)) != -1) {dos.write(buffer, 0, len);}dos.write(before);dos.write(after);dos.flush();int code = connection.getResponseCode();InputStream stream = connection.getInputStream();byte[] b = new byte[1024 * 10];int l;result = new StringBuilder();while ((l = stream.read(b)) != -1) {result.append(new String(b, 0, l, "utf-8"));}fis.close();dos.close();stream.close();} catch (MalformedURLException e) {} catch (ProtocolException e) {} catch (IOException e) {} finally {}if (result == null) {return null;} else {return result.toString();}}
更多相关文章
- android工程没有gen路径
- Android那些疑惑(2)-LayoutInflater中inflate方法参数的意义
- Android如何获取asset目录下所有文件的路径
- android 跳转并传递参数
- android 蓝牙ble app开发(二) -- 关键概念,连接参数,连接请求
- Android activity 参数传递