Android图片异步上传到PHP服务器实例


背景

       网上很多上传到java服务器上的,找了好久,找到了上传到php的了,思路跟我当初想的差不多,就是POST过去。废话不多说,直接上图看代码。


php代码:

<?php
define('GZ_PATH', dirname(__FILE__));

 $upload_name = "pushmessage";
 if (!isset($_FILES[$upload_name])) {
  echo "-1";
  exit(0);
 } else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
  echo "-2";
  exit(0);
 } else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
  echo "-3";
  exit(0);
 } else if (!isset($_FILES[$upload_name]['name'])) {
  echo "-4";
  exit(0);
 }
 
 $file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
 if ( !$file_size || ($file_size <= 0) ) {
  echo "-5";
  exit(0);
 }

 $file_name = $_FILES[$upload_name]['name'];
 if (strlen($file_name) == 0 ) {
  echo "-6";
  exit(0);
 }

 $file_name = "" . microtime() .".jpg";
 $file_name = str_replace(" ","-",$file_name);

 $save_path = GZ_PATH . "/picture/";
 if( !file_exists($save_path) )
 {
  mkdir($save_path);
 }

 $save_file = $save_path . $file_name;
 if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_file)) {
  echo "-7";
  exit(0);
 }
 $strUrl = $file_name;
 echo $strUrl;
?>


package com.insthub.ecmobile;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.insthub.BeeFramework.view.MyProgressDialog;

/*
 * 上传图片帮组类
 *
 *
 *
 */
public class PictureUploader {

 HttpURLConnection urlConn = null;

 public String filePath = "";
 public MyProgressDialog progress_bar;
 public Context context;

 public PictureUploader(String fPath, MyProgressDialog _progress_bar,Context _context) {
  filePath = fPath;
  progress_bar=_progress_bar;
  context=_context;
 }

 // 上传
 public void upload() {
  new Thread() {
   @Override
   public void run() {
    uploadImgFile();
   }
  }.start();
  
  
 }

 private void uploadImgFile() {
  boolean isOk=false;
  String end = "\r\n";
  String twoHyphens = "--";
  String boundary = "******";
  String result="";
  try {
   URL url = new URL(ECMobileAppConst.UPLOAD_PICTURE);
   HttpURLConnection httpURLConnection = (HttpURLConnection) url
     .openConnection();// http连接
   // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃
   // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
   httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
   // 允许输入输出流
   httpURLConnection.setDoInput(true);
   httpURLConnection.setDoOutput(true);
   httpURLConnection.setUseCaches(false);
   // 使用POST方法
   httpURLConnection.setRequestMethod("POST");
   httpURLConnection.setRequestProperty("Connection", "Keep-Alive");// 保持一直连接
   httpURLConnection.setRequestProperty("Charset", "UTF-8");// 编码
   httpURLConnection.setRequestProperty("Content-Type",
     "multipart/form-data;boundary=" + boundary);// POST传递过去的编码

   DataOutputStream dos = new DataOutputStream(
     httpURLConnection.getOutputStream());// 输出流
   dos.writeBytes(twoHyphens + boundary + end);
   dos.writeBytes("Content-Disposition: form-data; name=\"pushmessage\"; filename=\""
     + filePath.substring(filePath.lastIndexOf("/") + 1)
     + "\""
     + end);
   dos.writeBytes(end);

   FileInputStream fis = new FileInputStream(filePath);// 文件输入流,写入到内存中
   byte[] buffer = new byte[8192]; // 8k
   int count = 0;
   // 读取文件
   while ((count = fis.read(buffer)) != -1) {
    dos.write(buffer, 0, count);
   }
   fis.close();

   dos.writeBytes(end);
   dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
   dos.flush();

   if (httpURLConnection.getResponseCode() >= 200
     || httpURLConnection.getResponseCode() <= 206) {
    InputStream is = httpURLConnection.getInputStream();// http输入,即得到返回的结果
    InputStreamReader isr = new InputStreamReader(is, "utf-8");
    BufferedReader br = new BufferedReader(isr);
    result = br.readLine();

    // Toast.makeText(this, result,
    // Toast.LENGTH_LONG).show();//将结果输出
    Log.i("xxxxxxxxxxxxxxxxxx", "result:" + result);
    //成功
    if(!result.startsWith("-"))
    {
     isOk=true;
     
                    Message message = new Message();
                    message.what = 0;
                    message.obj = "";
                    handler.sendMessage(message);
    }

    dos.close();
    is.close();
    
   } else {
    //失败
   }
   httpURLConnection.disconnect();
   

  } catch (Exception e) {
   Log.e("xxxxxxxxxxxxxxxxxx", "e:" + e.getMessage());
   e.printStackTrace();
   //onError(filePath,progress_bar,e);
  }
  
  if(isOk)
  {
   //OnFinished(filePath,progress_bar,result);
  }
 }
 
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 0:
//                    String accessToken = (String)msg.obj;
                 OnFinished(filePath,progress_bar,"fweew.jpg");
                   
                    break;
            }

        }
    };

 public void OnFinished(String filePath, MyProgressDialog pb, String res) {
  Log.i("PictureUploader", "OnFinished is called");
 }
 
 public void onError(String filePath, MyProgressDialog pb, Exception ex) {
  Log.i("PictureUploader", "onError is called");
 }


}




private void uploadImage(File file, MyProgressDialog progress_bar) {
  
  new PictureUploader(file.getPath(), progress_bar,G0_PayClientActivity.this) {
   @Override
   public void onError(String filePath, MyProgressDialog pb,Exception ex) {
    pb.dismiss();
    ToastView toast5 = new ToastView(getApplicationContext(),"上传图片失败,超时错误!");
    toast5.setGravity(Gravity.CENTER, 0, 0);
    toast5.show();
   }

   @Override
   public void OnFinished(String filePath, MyProgressDialog pb,String res) {
    pb.dismiss();
    if (res.startsWith("-")) {
     ToastView toast5 = new ToastView(getApplicationContext(),"上传图片失败,错误码为:" + res + "!");
     toast5.setGravity(Gravity.CENTER, 0, 0);
     toast5.show();
     return;
    }
    tv_upload_file_name.setText(res);
    ToastView toast5 = new ToastView(getApplicationContext(),"上传成功,请提交付款!");
    toast5.setGravity(Gravity.CENTER, 0, 0);
    toast5.show();

    String filenameNew = Environment.getExternalStorageDirectory() + "/ECMobile/cache/upload.jpg";
    tv_show_picture.setBackgroundDrawable(Drawable.createFromPath(filenameNew));
    tv_show_picture.setText("");
   }
  }.upload();

 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值