android 图片上传到服务器

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>{

    @Override
    protected 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 connection
            ds.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];   //8k
            int 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;
    }
    @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");
            String res = jsonObject.getString("info");
            //成功上传一张图片后返回id
            mImgId = 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();
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值