`
xuela_net
  • 浏览: 503473 次
文章分类
社区版块
存档分类
最新评论

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的代码注掉,即可使用。


分享到:
评论

相关推荐

    Android图片上传服务器

    在Android应用开发中,图片上传至服务器是一项常见的需求,尤其在社交、电商或者任何需要用户分享内容的应用中。本文将详细讲解如何实现Android图片上传至服务器的完整过程,结合一个名为"UploadPhotoDemo"的示例...

    android 上传图片到服务器 net 与 php

    前一阵子整的android 上传图片到服务端,因为不善长java web 所以服务端是用.net写的,同时也写了个php版,里面包含客户端和服务端的代码,因为是抽取出来,使用时可能一些变量需要作相应修改。

    android客户端上传图片到服务器的简单实现

    在Android客户端上传图片到服务器的过程中,涉及到的主要知识点包括网络编程、HTTP请求、文件处理以及可能用到的第三方库。下面将详细阐述这些内容。 首先,Android客户端与服务器之间的通信通常基于HTTP或HTTPS...

    android上传图片到web服务器

    在Android平台上,将图片上传到Web服务器是一项常见的任务,尤其在开发涉及用户交互的应用时,如社交应用、电商应用等。这个"android上传图片到web服务器"的示例提供了使用HttpPost和MultiPartEntity方法实现这一...

    Android文件上传+服务器

    服务器端语言如Java、PHP、Node.js等都有对应的处理方式。 总结,Android中的文件上传涉及到网络请求、数据编码、权限管理等多个方面。`UploadTest`和`UploadExample`项目提供了实践参考,通过学习和理解这些示例,...

    android向php服务器传送数据

    在Android开发中,将数据发送到PHP服务器是一个常见的任务,特别是在构建移动应用时需要与后端进行交互。本文将深入探讨如何实现这个过程,并分享一个简单的DEMO。 首先,理解基本概念:Android是Google开发的开源...

    android 拍照后上传到php服务器的代码

    以上就是Android客户端拍照并上传到PHP服务器的基本流程。在实际应用中,还需要考虑错误处理、网络连接稳定性、用户权限管理、图片大小限制等问题。此外,为了提高用户体验,可以使用异步任务或服务来处理上传操作,...

    ( android上传图片至服务器

    在Android平台上,将图片上传至服务器是常见的任务之一,尤其在开发涉及用户交互的应用时,如社交应用或者图片分享平台。本教程将详细介绍如何通过Java后台处理和HTTPURLConnection实现这一功能。 首先,我们需要从...

    android向服务器上传图片

    在Android应用开发中,将图片上传到服务器是常见的需求,比如用户拍照或选择相册中的图片后分享到社交网络,或者存储云端。本篇将详细讲解如何在Android客户端(UpImageApp)实现向服务器(ImageServer)上传图片的...

    android上传文件到服务器(客户端加服务端源码)

    在Android平台上,将文件上传至服务器是一项常见的任务,尤其在开发涉及用户数据交互的应用时。本教程将深入探讨如何实现这一功能,同时提供客户端和服务端的源码示例,特别关注多文件上传的处理。 首先,客户端...

    android上传照片到服务器

    在Android开发中,将照片上传至服务器是一项常见的需求,尤其在社交应用或者云存储服务中。这个场景中,我们可以通过Android SDK提供的API结合网络请求库(如HttpClient或OkHttp)来实现。以下是一些关键的知识点: ...

    安卓拍照上传录像监控录屏相关-android录音上传到服务器上传使用AsyncTask异步任务.rar

    5. **服务器上传**: 文件上传通常涉及HTTP或HTTPS请求,使用`HttpURLConnection`或第三方库。例如,`OkHttp`提供了更简便的API来发送POST请求,包括文件上传。在`AsyncTask`的`doInBackground()`方法中,构建请求...

    图片带参数上传(android)

    本知识点主要讲解如何在Android 2.3.3版本的客户端中实现带参数的图片上传功能,并且会涉及到服务器端如何接收这些数据。 首先,我们需要了解Android中的图片选择流程。在2.3.3版本的Android中,我们可以使用Intent...

    ofu项目源码(Android+php服务器端)

    "ofu项目源码(Android+php服务器端)" 指的是一项包含客户端(Android应用)和服务器端(PHP基于ThinkPHP5.0框架)的完整项目源代码。这个项目的重点在于Android移动应用开发与后端服务的结合,涉及到了移动端与...

    android获取Php-web服务器端session并验证登陆

    这个过程涵盖了Android网络请求、PHP服务器端处理以及MySQL数据库操作等关键环节。 首先,我们从Android客户端开始。在Android中,通常使用HttpURLConnection或第三方库如OkHttp来发送HTTP请求。当用户尝试登录时,...

    Android实现上传文件到服务器实例详解

    本实例实现每隔5秒上传一次,通过服务器端获取手机上传过来的文件信息并做相应处理;采用Android+Struts2技术。 一、Android端实现文件上传 1)、新建一个Android项目命名为androidUpload,目录结构如下: 2)、...

    android完整的客户端与服务器源码-若水新闻

    【标题】"android完整的客户端与服务器源码-若水新闻" 涉及的主要知识点包括Android客户端开发、服务器端编程以及数据存储。 1. **Android客户端开发**:这是项目的核心部分,涉及到Android SDK的使用,包括...

    android json解析(包含服务器端,客户端)

    在Android应用开发中,JSON(JavaScript Object Notation)是一种常用的数据交换格式,它简洁、易于读写,并且被广泛应用于服务器与客户端之间的数据传输。本教程将深入讲解Android客户端和服务器端如何进行JSON解析...

    Android客户端读取PHP服务器的信息

    在Android开发中,与PHP服务器进行交互是常见的需求,用于获取和展示数据。在这个场景下,Android客户端将从PHP服务器请求信息,并通过ListView组件呈现这些信息。以下是对这个过程的详细解析: 首先,理解Android...

    okHttp 多图片上传(含服务器代码)--来自CSDN

    服务器端通常使用PHP、Java、Node.js等语言接收上传的图片。以PHP为例,你需要解析multipart/form-data格式的数据,接收文件并保存到服务器: ```php &lt;?php $dir = 'uploads/'; // 图片保存目录 foreach ($_FILES['...

Global site tag (gtag.js) - Google Analytics