有關於android上傳文件問題


O(∩_∩)O  要堅持把遇到的所有問題都總結到博客中

android上傳關鍵是在於將所有的信息都通過form表單的形式傳遞,首先一定要確定同服務器端的傳遞接口參數(坑爹啊。。。不知道參數調試了半天),模擬http頭信息,將所有的信息可以通過各種方式(HttpURLConnection, socket, ?httpclient?)傳遞到服務端, 這其中參數我忽略了數據長度的參數,結果下場很慘。。。。。。


話不多說 上代碼~~~


public static String post(Task task, Map<String, File> files) throws IOException {
		final String BOUNDARY = "---------------------------"
				+ java.util.UUID.randomUUID().toString(); // 數據分隔線
		final String endline = "--" + BOUNDARY + "--\r\n";// 數據結束標誌

		int fileDataLength = 0;
		for (Map.Entry<String, File> entry : files.entrySet()) {// 得到文件類型數據的總長度
			StringBuilder fileExplain = new StringBuilder();
			File file = entry.getValue();

			fileExplain.append("--");
			fileExplain.append(BOUNDARY);
			fileExplain.append("\r\n");
			fileExplain.append("Content-Disposition: form-data;name=\""
					+ entry.getKey() + "\";filename=\"" + file.getName()
					+ "\"\r\n");
			fileExplain.append("Content-Type: " + "application/octet-stream"
					+ "\r\n\r\n");
			fileExplain.append("\r\n");
			fileDataLength += fileExplain.length();
			if (file != null) {
				fileDataLength += file.length();
			}
		}

		StringBuilder textEntity = new StringBuilder();
		String data = getJson(getParams(task.params));
		textEntity.append("--");
		textEntity.append(BOUNDARY);
		textEntity.append("\r\n");
		textEntity.append("Content-Disposition: form-data; name=\"" + "data"
				+ "\"\r\n\r\n");
		textEntity.append(data);
		textEntity.append("\r\n");

		int dataLength = textEntity.toString().getBytes().length
				+ fileDataLength + endline.getBytes().length;
		
		if (task.url != null) {
			URL url = new URL(task.url);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5 * 1000);
			conn.setDoInput(true);// 允許輸入
			conn.setDoOutput(true);// 允許輸出
			conn.setUseCaches(false); // 不允許使用緩存
			conn.setRequestMethod("POST");
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Charsert", "UTF-8");
			conn.setRequestProperty("Content-Type", "multipart/form-data"
					+ ";boundary=" + BOUNDARY);
			conn.setRequestProperty("Content-Length",
					String.valueOf(dataLength));

			DataOutputStream outputStream = new DataOutputStream(
					conn.getOutputStream());

			outputStream.writeBytes(textEntity.toString());

			for (Map.Entry<String, File> entry : files.entrySet()) {
				StringBuilder fileEntity = new StringBuilder();
				File file = entry.getValue();
				if (file != null) {
					fileEntity.append("--");
					fileEntity.append(BOUNDARY);
					fileEntity.append("\r\n");
					fileEntity.append("Content-Disposition: form-data;name=\""
							+ entry.getKey() + "\";filename=\""
							+ entry.getValue().getName() + "\"\r\n");
					fileEntity.append("Content-Type: "
							+ "application/octet-stream" + "\r\n\r\n");
					outputStream.writeBytes(fileEntity.toString());

					FileInputStream fis = new FileInputStream(file);
					byte[] buffer = new byte[1024];
					int len = 0;
					while ((len = fis.read(buffer)) != -1) {
						outputStream.write(buffer, 0, len);
						outputStream.flush();
					}
					outputStream.write("\r\n".getBytes());
					fis.close();
				}
			}
			outputStream.writeBytes(endline);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			if (conn.getResponseCode() != 200) {// 讀取web服務器返回的數據,判斷請求碼是否爲200,如果不是200,代表請求失敗
				return "error";
			}

			String result = "";
			String line = null;
			while ((line = reader.readLine()) != null) {
				result = result + line;
			}
			outputStream.flush();
			outputStream.close();
			reader.close();
			return result;
		}else{
			return "error";
		}
	}


Task 中封裝了 一些關於上傳任務的信息,Map 參數 主要用於存放上傳文件。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章