Android文件上传

原创
2013/09/12 09:08
阅读数 581
/**
	 * 上传文件
	 * 
	 * @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();
		}
	}
展开阅读全文
加载中

作者的其它热门文章

0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部