Android单文件上传到服务器

public class HttpManager {

	private static final String TAG = "HttpManager";
	private static final String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";

	/**
	 * 
	 * @param uploadFile
	 *            需要上传的文件名
	 * @param newFileName
	 *            上传的文件名称,不填写将为uploadFile的名称
	 * @param urlStr
	 *            上传的服务器的路径
	 * @throws IOException
	 */
	public static String uploadForm(File uploadFile, String newFileName, String urlStr) throws IOException {
		String fileFormName = "log_file";
		if (newFileName == null || newFileName.trim().equals("")) {
			newFileName = uploadFile.getName();
		}

		StringBuilder sb = new StringBuilder();
		/*        *//**
					 * 普通的表单数据
					 *//*
						 * for (String key : params.keySet()) { sb.append("--" +
						 * BOUNDARY + "\r\n"); sb.append(
						 * "Content-Disposition: form-data; name=\"" + key +
						 * "\"" + "\r\n"); sb.append("\r\n");
						 * sb.append(params.get(key) + "\r\n"); }
						 */
		/**
		 * 上传文件的头
		 */
		sb.append("--" + BOUNDARY + "\r\n");
		sb.append("Content-Disposition: form-data; name=\"" + fileFormName + "\"; filename=\"" + newFileName + "\""
				+ "\r\n");
		sb.append("Content-Type: text/html" + "\r\n");// 如果服务器端有文件类型的校验,必须明确指定ContentType
		sb.append("\r\n");

		byte[] headerInfo = sb.toString().getBytes("UTF-8");
		byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
		conn.setRequestProperty("Content-Length",
				String.valueOf(headerInfo.length + uploadFile.length() + endInfo.length));

		conn.setDoOutput(true);

		OutputStream out = conn.getOutputStream();
		InputStream in = new FileInputStream(uploadFile);
		out.write(headerInfo);

		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) != -1)
			out.write(buf, 0, len);

		out.write(endInfo);
		in.close();
		out.close();

		if (conn.getResponseCode() == 200) {

			InputStream inputStream = conn.getInputStream();
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			byte[] bs = new byte[1024];
			int len1 = 0;
			while ((len1 = inputStream.read(bs)) != -1) {
				stream.write(bs, 0, len1);
			}
			String string = new String(stream.toByteArray());
			LogHelper.d(TAG, "返回值:" + string);

			return string;
		}

		return null;

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值