设为首页 收藏本站
查看: 635|回复: 0

[经验分享] android 图片上传java,php服务器

[复制链接]

尚未签到

发表于 2017-4-3 08:44:47 | 显示全部楼层 |阅读模式
  项目上传图片到后台,前端总是传不上去,翻阅代码,详细查看,原来是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的代码注掉,即可使用。
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-359381-1-1.html 上篇帖子: PHP安全基础原则与方法 下篇帖子: PHP缓存技术:memcache函数详解之三
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表