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) { } } }?
详细解决方案
android上传资料至服务器
热度:75 发布时间:2016-05-01 13:33:12.0
相关解决方案
- android 读取byte[]中的元素解决方案
- android 标题栏兑现方式
- android 中Activity向BroadcastReceiver发送数据,该怎么解决
- Android 4.0 为什么模拟器老是提示小弟我谷歌拼音输入法已停止
- android:getSharedPreferences() 这是哪个类的方法解决思路
- android 怎么判断一个程序是否联网
- android 大量数据按周分组,该如何解决
- android RadioButton如何设置默认选中
- ksoap2-android-这个包,连接webService怎么设置超时
- android 怎么重新设置锚点
- android UI界面设计解决方案
- android 图片对象获取的有关问题
- android 怎么调用淘宝支付宝接口
- Android 沿袭InputMethodService自定义输入法
- android 关于服务连接的疑义
- android 两个activity如何通信
- android 怎么实现对view的放大和缩小
- android 教程解决方法
- android ID,该如何处理
- 准备复习2-3个月,看java+android,请问有经验者,怎么看效果最好》
- android UI线程与AsyncTask的有关问题
- android(java)中的java.net能不能和c#的system.net.sockets进行tcp通信,该如何解决
- android ListView 中的onItemClick Intent 没法跳转
- android(java) 中文乱码的有关问题
- c#c++,android,ios(iphone),php,java视屏课程 散分
- android Post文件到ASP.NET的有关问题,能收到参数收不到文件
- RIM 替 Android 开发者提供免费的 PlayBook!2月13日前
- android 动态设立控件高度
- Android test project 编译方法
- android -相机使用教程(1)解决方法