1. 程式人生 > 其它 >JAVA用post請求上傳二進位制檔案

JAVA用post請求上傳二進位制檔案

/**
	 * 多檔案上傳的方法
	 * 
	 * @param actionUrl:上傳的路徑
	 * @param uploadFilePaths:需要上傳的檔案路徑,陣列
	 * @return
	 */
	@SuppressWarnings("finally")
	public static String uploadFile(String actionUrl, String[] uploadFilePaths) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		
		DataOutputStream ds = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		StringBuffer resultBuffer = new StringBuffer();
		String tempLine = null;
		
		 try {
			// 統一資源
			 URL url = new URL(actionUrl);
			// 連線類的父類,抽象類
			 URLConnection urlConnection = url.openConnection();
			// http的連線類
			 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			// 設定是否從httpUrlConnection讀入,預設情況下是true;
			 httpURLConnection.setDoInput(true);
			// 設定是否向httpUrlConnection輸出
			 httpURLConnection.setDoOutput(true);
			// Post 請求不能使用快取
			 httpURLConnection.setUseCaches(false);
			// 設定請求的方法,預設是GET
			 httpURLConnection.setRequestMethod("POST");
			// 設定字元編碼連線引數
			 httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			// 設定字元編碼
			 httpURLConnection.setRequestProperty("Charset", "UTF-8");
			// 設定請求內容型別
			 httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			 
			// 設定DataOutputStream
			 ds = new DataOutputStream(httpURLConnection.getOutputStream());
			 for (int i = 0; i < uploadFilePaths.length; i++) {
				 String uploadFile = uploadFilePaths[i];
				 String filename = uploadFile.substring(uploadFile.lastIndexOf("\\") + 1);
				 ds.writeBytes(twoHyphens + boundary + end);
				 ds.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename
						 + "\"" + end);
				 ds.writeBytes(end); 
				 FileInputStream fStream = new FileInputStream(uploadFile);
				 int bufferSize = 1024;
				 byte[] buffer = new byte[bufferSize];
				 int length = -1;
				 while ((length = fStream.read(buffer)) != -1) {
					 ds.write(buffer, 0, length);
				 }
				 ds.writeBytes(end);
				 /* close streams */
				 fStream.close();
			 }
			 ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			 /* close streams */
			 ds.flush();
			 if (httpURLConnection.getResponseCode() >= 300) {
				 throw new Exception(
						 "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
			 }
			 if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				 inputStream = httpURLConnection.getInputStream();
				 inputStreamReader = new InputStreamReader(inputStream);
				 reader = new BufferedReader(inputStreamReader);
				 tempLine = null;
				 resultBuffer = new StringBuffer();
				 while ((tempLine = reader.readLine()) != null) {
					 resultBuffer.append(tempLine);
					 resultBuffer.append("\n");
				 }
			 }
		 }catch(Exception e) {
			 e.printStackTrace();
		 }finally {
			 if (ds != null) {
				 try {
					 ds.close();
				 } catch (IOException e) {
					// TODO Auto-generated catch block
					 e.printStackTrace();
				 }
			 }
			 if (reader != null) {
				 try {
					 reader.close();
				 } catch (IOException e) {
					// TODO Auto-generated catch block
					 e.printStackTrace();
				 }
			 }
			 if (inputStreamReader != null) {
				 try {
					 inputStreamReader.close();
				 } catch (IOException e) {
					// TODO Auto-generated catch block
					 e.printStackTrace();
				 }
			 }
			 if (inputStream != null) {
				 try {
					 inputStream.close();
				 } catch (IOException e) {
					// TODO Auto-generated catch block
					 e.printStackTrace();
				 }
			 }
			 return resultBuffer.toString();
		 }
	}

 轉自:【JAVA】通過HttpURLConnection 上傳和下載檔案(二) - H__D - 部落格園 (cnblogs.com)