android 图片上传java,php服务器

项目上传图片到后台,前端总是传不上去,翻阅代码,详细查看,原来是php的头和java的不同。

总体的思路是,可以拍照上传,也可以本地上传。利用onActivityResult,从返回的Intent中得到Bitmap对象。

如果是文件系统中的图片又分为content://开头和file://开头,给予判断即可。

又:java和php服务器后台传输数据时,解析不同的头,下面上代码:

public class CameraTest extends Activity {
Bitmap photo = null;
String filename="";
String picPath="";
ImageView imageview;
Button mPic,mUpload;
static String path="http://xxx.xxx.x.xx/xxxr.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_test);
imageview=(ImageView) findViewById(R.id.imageview);
mPic=(Button) findViewById(R.id.pic);
mUpload=(Button) findViewById(R.id.upload);
mUpload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(photo!=null){
String srcPath = Environment.getExternalStorageDirectory()+ "/imgs/"+filename;
new CommentAsyncTask().execute(srcPath);
}
}
});
mPic.setOnClickListener(new Onclicklistenerimpl2());
}
class CommentAsyncTask extends AsyncTask<String, Integer, String> {


@Override
protected String doInBackground(String... params) {
uploadFile(params[0]);
return "";
}


@Override
protected void onPostExecute(String result) {
//
super.onPostExecute(result);
}
}
// ///上传图片/
private class Onclicklistenerimpl2 implements OnClickListener {
private String[] method = { "拍照上传", "本地上传" };


@Override
public void onClick(View v) {
dialog();



}


private void dialog() {
AlertDialog ad = new AlertDialog.Builder(CameraTest.this)
// .setIcon(R.drawable.ic_launcher)
.setItems(method, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
String state = Environment
.getExternalStorageState();


if (state.equals(Environment.MEDIA_MOUNTED)) {


Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");


startActivityForResult(intent, 11);


} else {


Toast.makeText(CameraTest.this,


"sdcard is missing", Toast.LENGTH_LONG)
.show();


}


break;
case 1:
/***

* 这个是调用android内置的intent,来过滤图片文件 ,同时也可以过滤其他的
*/


Intent intent = new Intent();


intent.setType("image/*");


intent.setAction(Intent.ACTION_GET_CONTENT);


startActivityForResult(intent, 12);


break;
}
// Toast.makeText(getApplicationContext(),
// method[which], Toast.LENGTH_SHORT).show();
}
}).create();
ad.show();
}


}
private void uploadFile(String srcPath){
// MyApp ma = (MyApp) getApplicationContext();
 
String uploadUrl = path;
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try {
URL url = new URL(uploadUrl);
 
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection
.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
 
/*this part is for java used
 * httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);*/
/*this part is for php used*/
httpURLConnection.setRequestProperty("enctype",
                     "multipart/form-data;boundary="+boundary);

DataOutputStream dos = new DataOutputStream(
httpURLConnection.getOutputStream());
 
/*this part is for java used
 * dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)+ "\"" + end);
dos.writeBytes(end);*/
 
Log.i("CAMERA",srcPath);
FileInputStream fis = new FileInputStream(srcPath);
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();

InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result="";
int i=0;
while(i<100){
 result= br.readLine();
 if(result!=null&&!"".equals(result)){
 Log.i("CAMERA", result);//tishi
 }
 i++;
}
Log.i("CAMERA", br.read()+"---br.read()----");//tishi
 
Looper.prepare();
Toast.makeText(CameraTest.this, result, Toast.LENGTH_LONG)
.show();
dos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
// setTitle(e.getMessage());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//receive camera message
if(11==requestCode){
Uri uri = data.getData();


if (uri != null) {


photo = BitmapFactory.decodeFile(uri.getPath());
// imageview.setImageBitmap(photo);
}


if (photo == null) {


Bundle bundle = data.getExtras();


if (bundle != null) {


photo = (Bitmap) bundle.get("data");
} else {


Toast.makeText(CameraTest.this,


"get image falure",


Toast.LENGTH_LONG).show();


return;


}


}
imageview.setImageBitmap(photo);
storeImgs(photo);
}


//receive local message
if(12==requestCode){
             /**
          * 当选择的图片不为空的话,在获取到图片的途径    
          */
             Uri uri = data.getData();


            Log.i("mylog", "local uri = "+ uri);  


            try {  
            //MediaStore
                 String[] pojo = {MediaStore.Images.Media.DATA};  


                Cursor cursor = this.managedQuery(uri, pojo, null, null,null);  


               if(cursor!=null)  
              {
                    ContentResolver cr = this.getContentResolver();  


                     int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  


                    cursor.moveToFirst();  


                   String path = cursor.getString(colunm_index);  
                   Log.i("CAMERA",path+"-----------------------");


                   /***  


                      * 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了,这样的话,我们判断文件的后缀名  


                      * 如果是图片格式的话,那么才可以     


                     */ 


                     if(path.endsWith("jpg")||path.endsWith("png"))  


                    {  


                        picPath = path;  


                        photo = BitmapFactory.decodeStream(cr.openInputStream(uri));  


                         imageview.setImageBitmap(photo);  


                    }else{
                     
                    }  


                }else{
                String fileName;
                String str=uri.toString().substring(0, uri.toString().indexOf("/"));
                Log.i("mylog","------"+str);
                if("file:".equals(str)){
                fileName = uri.toString();
                      fileName = uri.toString().replace("file://", "");
                //替换file://
                     if(!fileName.startsWith("/mnt")){
                //加上"/mnt"头
                   fileName += "/mnt"; 
                }
                imageview.setImageBitmap(BitmapManager.convertToBitmap(fileName, 300, 500));
                Log.i("mylog","wrong..------"+fileName);
                }


                }    


             } catch (Exception e) {  
      }  
            storeImgs(photo);        
}


}


private void storeImgs(Bitmap bitmap) {
String pictureDir = "";


FileOutputStream fos = null;


BufferedOutputStream bos = null;


ByteArrayOutputStream baos = null;


try {


baos = new ByteArrayOutputStream();


bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);


byte[] byteArray = baos.toByteArray();


String saveDir = Environment.getExternalStorageDirectory()


+ "/imgs";


File dir = new File(saveDir);


if (!dir.exists()) {


dir.mkdir();
}
//根据系统时间创建名称
filename=Calendar.getInstance().getTimeInMillis()+".jpg";
File file = new File(saveDir, filename);


file.delete();


if (!file.exists()) {


file.createNewFile();


}


fos = new FileOutputStream(file);


bos = new BufferedOutputStream(fos);


bos.write(byteArray);


pictureDir = file.getPath();


} catch (Exception e) {


e.printStackTrace();


} finally {


if (baos != null) {


try {


baos.close();


} catch (Exception e) {


e.printStackTrace();


}


}


if (bos != null) {


try {


bos.close();


} catch (Exception e) {


e.printStackTrace();
}
}
if (fos != null) {


try {


fos.close();


} catch (Exception e) {


e.printStackTrace();


}


}


}


}


// ///
}

需要注意的就是upload方法,在这里。我注释掉的部分是java服务器的代码,需要用时,把php的代码注掉,即可使用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值