합쭈기 programming

http connect - 파일 업로드 본문

Java/Android

http connect - 파일 업로드

innocent_k 2015. 4. 13. 10:38
protected void requestFileUpload(final String urlString, final String fileName) {

		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub

				String lineEnd = "\r\n";
				String twoHyphens = "--";
				String boundary = "*****";

				try {

					FileInputStream mFileInputStream = new FileInputStream(
							fileName);
					URL connectUrl = new URL(urlString);
					Log.d("Test", "mFileInputStream  is " + mFileInputStream);

					// open connection
					HttpURLConnection conn = (HttpURLConnection) connectUrl
							.openConnection();
					conn.setDoInput(true);
					conn.setDoOutput(true);
					conn.setUseCaches(false);
					conn.setRequestMethod("POST");
					conn.setRequestProperty("Connection", "Keep-Alive");
					conn.setRequestProperty("Content-Type",
							"multipart/form-data;boundary=" + boundary);

					// write data
					DataOutputStream dos = new DataOutputStream(conn
							.getOutputStream());
					dos.writeBytes(twoHyphens + boundary + lineEnd);
					dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
							+ fileName + "\"" + lineEnd);
					dos.writeBytes(lineEnd);

					int bytesAvailable = mFileInputStream.available();
					int maxBufferSize = 1024;
					int bufferSize = Math.min(bytesAvailable, maxBufferSize);

					byte[] buffer = new byte[bufferSize];
					int bytesRead = mFileInputStream
							.read(buffer, 0, bufferSize);

					Log.d("Test", "image byte is " + bytesRead);

					// read image
					while (bytesRead > 0) {
						dos.write(buffer, 0, bufferSize);
						bytesAvailable = mFileInputStream.available();
						bufferSize = Math.min(bytesAvailable, maxBufferSize);
						bytesRead = mFileInputStream
								.read(buffer, 0, bufferSize);
					}

					dos.writeBytes(lineEnd);
					dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

					// close streams
					Log.e("Test", "File is written");
					mFileInputStream.close();
					dos.flush(); // finish upload...

					// get response
					int ch;
					InputStream is = conn.getInputStream();
					StringBuffer b = new StringBuffer();
					while ((ch = is.read()) != -1) {
						b.append((char) ch);
					}
					String s = b.toString();
					JSONObject json = new JSONObject(s);

					Util.sendHandleMessage(handle, msgWhat, json);
					// mEdityEntry.setText(s);
					dos.close();

				} catch (Exception e) {
					Log.d("Test", "exception " + e.getMessage());
					Util.sendHandleMessage(handle, HandleParam.ERROR,
							e.toString());
					// TODO: handle exception
				}

			}

		}).start();
	}

'Java > Android' 카테고리의 다른 글

SharedPreferences  (0) 2015.04.13
http connect - json  (0) 2015.04.13
hidden keyboard  (0) 2015.04.13
fading actionbar 소스  (0) 2015.04.07
button xml로 만들기  (0) 2015.04.07