当前位置: 代码迷 >> Android >> android上传资料至服务器
  详细解决方案

android上传资料至服务器

热度:75   发布时间:2016-05-01 13:33:12.0
android上传文件至服务器

class FileUploadTask extends AsyncTask<Object, Integer, String> {		// private ProgressDialog dialog = null;		Dialog dialog = new Dialog(PhotoUploadActivity.this,				R.style.ProgressBarDialog);		String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成		String PREFIX = "--", LINE_END = "\r\n";		String CONTENT_TYPE = "multipart/form-data"; // 内容类型		File uploadFile = new File(filePath);		long totalSize = uploadFile.length(); // Get size of file, bytes		ProgressBar mProgress;		TextView mProgress_txt;		@Override		protected void onPreExecute() {			/*			 * dialog = new ProgressDialog(PhotoUploadActivity.this);			 * dialog.setTitle("正在上传...");			 * dialog.setMessage("0k/"+totalSize/1000+"k");			 * dialog.setIndeterminate(false);			 * dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);			 * dialog.setProgress(0); dialog.show();			 */			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);			dialog.setContentView(R.layout.dialog_photo_progressbar);			dialog.setCancelable(true);			DisplayMetrics dm = PhotoUploadActivity.this					.getApplicationContext().getResources().getDisplayMetrics();			int width = dm.widthPixels;			WindowManager.LayoutParams params = dialog.getWindow()					.getAttributes();			params.width = 9 * width / 10;			dialog.getWindow().setAttributes(params);			mProgress = (ProgressBar) dialog					.findViewById(R.id.progress_horizontal);			mProgress_txt = (TextView) dialog.findViewById(R.id.progress_txt);			mProgress.setMax(100);			mProgress.setProgress(0);			mProgress.setIndeterminate(false);			dialog.setCancelable(false);// 设置这个对话框不能被用户按[返回键]而取消掉,但测试发现如果用户按了KeyEvent.KEYCODE_SEARCH,对话框还是会Dismiss掉			// 由于设置alertDialog.setCancelable(false);			// 发现如果用户按了KeyEvent.KEYCODE_SEARCH,对话框还是会Dismiss掉,这里的setOnKeyListener作用就是屏蔽用户按下KeyEvent.KEYCODE_SEARCH			dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {				public boolean onKey(DialogInterface dialog, int keyCode,						KeyEvent event) {					if (keyCode == KeyEvent.KEYCODE_SEARCH) {						return true;					} else {						return false; // 默认返回 false					}				}			});			dialog.show();			dialog.getWindow()					.setType(WindowManager.LayoutParams.TYPE_KEYGUARD);		}		@Override		protected String doInBackground(Object... arg0) {			String result = "";			long length = 0;			int progress;			int bytesRead, bytesAvailable, bufferSize;			byte[] buffer;			int maxBufferSize = 10 * 1024;// 10KB			try {				URL url = new URL(actionUrl);				HttpURLConnection conn = (HttpURLConnection) url						.openConnection();				// Set size of every block for post				conn.setChunkedStreamingMode(128 * 1024);// 128KB				conn.setReadTimeout(TIME_OUT);				conn.setConnectTimeout(TIME_OUT);				conn.setDoInput(true); // 允许输入流				conn.setDoOutput(true); // 允许输出流				conn.setUseCaches(false); // 不允许使用缓存				conn.setRequestMethod("POST"); // 请求方式				conn.setRequestProperty("Charset", CHARSET); // 设置编码				conn.setRequestProperty("connection", "keep-alive");				conn.setRequestProperty("Content-Type", CONTENT_TYPE						+ ";boundary=" + BOUNDARY);				if (uploadFile != null) {					/**					 * 当文件不为空,把文件包装并且上传					 */					DataOutputStream dos = new DataOutputStream(conn							.getOutputStream());					StringBuffer sb = new StringBuffer();					sb.append(PREFIX);					sb.append(BOUNDARY);					sb.append(LINE_END);					/**					 * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件					 * filename是文件的名字,包含后缀名的 比如:abc.png					 */					sb.append("Content-Disposition: form-data; name=\"myFile\"; filename=\"" + java.net.URLEncoder.encode(uploadFile									.getName(), "UTF-8") + "\"" + LINE_END);					sb.append("Content-Type: application/octet-stream; charset="+ CHARSET + LINE_END);					sb.append(LINE_END);					dos.write(sb.toString().getBytes());					InputStream is = new FileInputStream(uploadFile);					bytesAvailable = is.available();					bufferSize = Math.min(bytesAvailable, maxBufferSize);// 设置每次写入的大小					buffer = new byte[bufferSize];					// Read file					bytesRead = is.read(buffer, 0, bufferSize);					while (bytesRead > 0) {						dos.write(buffer, 0, bufferSize);						length += bufferSize;						Thread.sleep(500);						progress = (int) ((length * 100) / totalSize);						publishProgress(progress, (int) length);						bytesAvailable = is.available();						bufferSize = Math.min(bytesAvailable, maxBufferSize);						bytesRead = is.read(buffer, 0, bufferSize);					}					byte[] bytes = new byte[1024];					int len = 0;					while ((len = is.read(bytes)) != -1) {						dos.write(bytes, 0, len);					}					is.close();					dos.write(LINE_END.getBytes());					// 请求结束标志					byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)							.getBytes();					dos.write(end_data);					dos.flush();					publishProgress(100, (int) length);					/**					 * 获取响应码 200=成功 当响应成功,获取响应的流					 */					int res = conn.getResponseCode();					Log.e(TAG, "response code:" + res);					if (res == 200) {						Log.e(TAG, "request success");						InputStream input = conn.getInputStream();						StringBuffer sb1 = new StringBuffer();						int ss;						while ((ss = input.read()) != -1) {							sb1.append((char) ss);						}						result = sb1.toString();						Log.e(TAG, "result : " + result + "fffff"								+ new File(filePath).getName() + "呵呵呵" + sb1);					} else {						Log.e(TAG, "request error");					}				}			} catch (Exception ex) {			}			return result;		}		@Override		protected void onProgressUpdate(Integer... progress) {			// dialog.setProgress(progress[0]);			// dialog.setMessage(progress[1]/1000+"k/"+totalSize/1000+"k");			Log.i(TAG, "已经上传----->" + progress[1] / 1000 + "k/" + totalSize					/ 1000 + "k");			mProgress.setProgress(progress[0]);			mProgress_txt.setText(progress[1] / 1000 + "k/" + totalSize / 1000					+ "k" + "  " + progress[1] * 100 / totalSize + "%");		}		@Override		protected void onPostExecute(String result) {			try {				if ("1".equals(result)) {					Toast.makeText(PhotoUploadActivity.this, "上传成功!",							Toast.LENGTH_LONG).show();				} else {					Toast.makeText(PhotoUploadActivity.this, "上传失败!",							Toast.LENGTH_LONG).show();				}			} catch (Exception e) {			} finally {				try {					dialog.dismiss();				} catch (Exception e) {				}			}		}
?
  相关解决方案