android 图片上传到服务器
2016-05-18 08:38
381 查看
1、java后台
public class MyAsync extends AsyncTask<String,String,String>{ @Override protected String doInBackground(String... params) { URL url = null; try { url = new URL(params[0]); Log.e("url",params[0]); // 发送POST请求必须设置如下两行 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "text/html"); conn.setRequestProperty("Content-Type", "multipart/form-data"); conn.setRequestProperty("Cache-Control", "no-cache"); conn.setRequestProperty("Charsert", "UTF-8"); conn.connect(); conn.setConnectTimeout(10000); OutputStream out = conn.getOutputStream();
File file = new File(mFileName);
DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] buffer = new byte[1024]; while ((bytes = in.read(buffer)) != -1) { out.write(buffer, 0, bytes); } in.close(); out.flush(); out.close(); BufferedReader br = new BufferedReader(new InputStreamReader(conn .getInputStream())); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } conn.disconnect(); return sb.toString(); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (ProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return null;
@Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); try { JSONObject jsonObject = new JSONObject(result); String message = jsonObject.getString("message");
Toast.makeText(GatherMsgActivity.this,message,Toast.LENGTH_SHORT).show();} catch (JSONException e) { e.printStackTrace(); } }}
2、php后台
public class MyAsync extends AsyncTask<String,String,String>{@Overrideprotected String doInBackground(String... params) {
String end = "\r\n";String twoHyphens = "--";String boundary = "*****";String fileName = "test.jpg"; //报文中的文件名参数try{URL url = new URL(Config.UPIMGURL);HttpURLConnection con = (HttpURLConnection) url.openConnection();/* Output to the connection. Default is false,set to true because post method must write something to the connection */con.setDoOutput(true);/* Read from the connection. Default is true.*/con.setDoInput(true);/* Post cannot use caches */con.setUseCaches(false);/* Set the post method. Default is GET*/con.setRequestMethod("POST");/* 设置请求属性 */con.setRequestProperty("Connection", "Keep-Alive");con.setRequestProperty("Charset", "UTF-8");con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);/* 设置DataOutputStream,getOutputStream中默认调用connect()*/DataOutputStream ds = new DataOutputStream(con.getOutputStream()); //output to the connectionds.writeBytes(twoHyphens + boundary + end);ds.writeBytes("Content-Disposition: form-data; " + "name=\"file\";filename=\"" + fileName + "\"" + end);ds.writeBytes(end);/* 取得文件的FileInputStream params[0]为图片保存绝对路径 */Log.e("xxxx",params[0]);FileInputStream fStream = new FileInputStream(params[0]);/* 设置每次写入8192bytes */int bufferSize = 8192;byte[] buffer = new byte[bufferSize]; //8kint length = -1;/* 从文件读取数据至缓冲区 */while ((length = fStream.read(buffer)) != -1){/* 将资料写入DataOutputStream中 */ds.write(buffer, 0, length);}ds.writeBytes(end);ds.writeBytes(twoHyphens + boundary + twoHyphens + end);/* 关闭流,写入的东西自动生成Http正文*/fStream.close();/* 关闭DataOutputStream */ds.close();/* 从返回的输入流读取响应信息 */InputStream is = con.getInputStream(); //input from the connection 正式建立HTTP连接int ch;StringBuffer b = new StringBuffer();while ((ch = is.read()) != -1){b.append((char) ch);}/* 显示网页响应内容 */return b.toString();} catch (Exception e){System.out.println( e.getMessage());}return null;}@Overrideprotected void onPostExecute(String result) {// TODO Auto-generated method stubsuper.onPostExecute(result);try {JSONObject jsonObject = new JSONObject(result);// String message = jsonObject.getString("message");String res = jsonObject.getString("info");//成功上传一张图片后返回idmImgId = jsonObject.getInt("id");idList.add(mImgId+"");//所有图片都上传成功后if(imgList.size()==idList.size()){if(isUpdate){updateMonitorPoint();}else{submitMonitorPoint();}}// Toast.makeText(GatherMsgActivity.this,message,Toast.LENGTH_SHORT).show();} catch (JSONException e) {e.printStackTrace();}}}
相关文章推荐
- Android 关于IPC机制的理解(二)
- 在Android上打造属于自己的Rxjava框架(一)基础篇
- Android Intent最全面的解析
- Android官方开发文档Training系列课程中文版:OpenGL绘图之环境配置
- Android中View(视图)绘制不同状态背景图片原理深入分析以及StateListDrawable使用详解
- Android 制作简易浏览器源码
- Android列表RecyclerView的用法
- Android开发用的名词
- Android Studio Plugin-Translate English to Chinese
- Android Drawable - Bitmap Drawable使用详解(附图)
- Android 屏幕适配方案
- Android 启动模拟器是出现“Failed to allocate memory:8”
- 安卓系统文件夹及其文件解析
- Android快速开发
- Android中Context详解---- 你所不知道的Context
- Android下自适应屏幕
- Android中使用commons-codec-1.x 出错解释
- Android多渠道打包这样做才酸爽!?
- android布局 parent
- Android Fragment应用及原理