android拍照上传和本地上传功能实现了

 

android拍照上传和本地上传功能实现了


直接上代码

Pic.java

 

package com.webview;

import java.io.FileNotFoundException; 
import com.http.HTTPRequestHelper;
import android.app.Activity; 
import android.app.AlertDialog;
import android.content.ContentResolver; 
import android.content.DialogInterface;
import android.content.Intent; 
import android.database.Cursor;
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log; 
import android.view.MotionEvent;
import android.view.View; 
import android.widget.Button; 
import android.widget.ImageView; 
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Locale;

import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.app.AlertDialog;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

public class Pic extends Activity

   private String newName="image.jpg";
   //private String uploadFile="/mnt/sdcard/DCIM/Camera/Icon-Small.png";
   private String actionUrl="http://a.cn//android_upload_o.php";
   private String path;
   private Uri uri;
   private final int  REQ_CODE_CAMERA =1;
   private final int REQ_CODE_PICTURE =0;
   private String imgurl;
   private File tempfile;
      public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.pic); 
    
        Button bpic = (Button)findViewById(R.id.bpic); 
        bpic.setOnClickListener(new Button.OnClickListener(){ 
            public void onClick(View v) {
               /*
             Intent i = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(i, REQ_CODE_CAMERA);
              */
             ImageCapture();
            }           
        });
     
        Button button = (Button)findViewById(R.id.b01); 
        button.setOnClickListener(new Button.OnClickListener(){ 
            @Override 
            public void onClick(View v) { 
                Intent intent = new Intent(); 
                /* 开启Pictures画面Type设定为image */ 
                intent.setType("image/*"); 
                /* 使用Intent.ACTION_GET_CONTENT这个Action */ 
                intent.setAction(Intent.ACTION_GET_CONTENT);            
                /* 取得相片后返回本画面 */ 
                startActivityForResult(intent, REQ_CODE_PICTURE); 
            }          
        }); 
    }     
   public void ImageCapture() {
  File DatalDir = Environment.getExternalStorageDirectory();
  File myDir = new File(DatalDir, "/DCIM/Camera");
  myDir.mkdirs();
  String mDirectoryname = DatalDir.toString() + "/DCIM/Camera";
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hhmmss",
    Locale.SIMPLIFIED_CHINESE);
  tempfile = new File(mDirectoryname, sdf.format(new Date())
    + ".jpg");
  if (tempfile.isFile())
   tempfile.delete();
  Uri Imagefile = Uri.fromFile(tempfile);
       
  Intent cameraIntent = new Intent(
    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Imagefile);
    startActivityForResult(cameraIntent, REQ_CODE_CAMERA);
 }
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    { 
     super.onActivityResult(requestCode, resultCode, data); 
        if (resultCode == RESULT_OK)
        {     
         if(requestCode==REQ_CODE_CAMERA)
         {
               System.out.println("ar"+tempfile.getPath());
               uploadFile(tempfile.getPath());
         }
         else if(requestCode==REQ_CODE_PICTURE)
         {
                uri = data.getData(); 
                path=  getAbsoluteImagePath(uri);
                System.out.println("a"+path);
                uploadFile(path);
         }
        }  
    } 

 public void onLongPress(MotionEvent e) {
 
 }

 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,float distanceY) {
  return false;
 }

 public void onShowPress(MotionEvent e) {
 
 }

 public boolean onSingleTapUp(MotionEvent e) {
  return false;
 }
 private Handler handlers = new Handler(){
  public void dispatchMessage(android.os.Message msg) {
   return;
  };
 };
 protected String getAbsoluteImagePath(Uri uri)  
   {  
   // can post image  
   String [] proj={MediaStore.Images.Media.DATA};  
   Cursor cursor = managedQuery( uri,  
   proj, // Which columns to return  
   null, // WHERE clause; which rows to return (all rows)  
   null, // WHERE clause selection arguments (none)  
   null); // Order-by clause (ascending by name)  
    
   int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
   cursor.moveToFirst();  
    
   return cursor.getString(column_index);  
   }
 
   /* 上传文件吹Server的method */
   private void uploadFile(String path)
   {
     String end = "\r\n";
     String twoHyphens = "--";
     String boundary = "*****";
     try
     {
       URL url =new URL(actionUrl);
       HttpURLConnection con=(HttpURLConnection)url.openConnection(); 
       /* 允许Input、Output,不使用Cache */
       con.setDoInput(true);
       con.setDoOutput(true);
       con.setUseCaches(false);
       /* 设定传送的method=POST */
       con.setRequestMethod("POST");
       /* setRequestProperty */
       con.setRequestProperty("Connection", "Keep-Alive");
       con.setRequestProperty("Charset", "UTF-8");
       con.setRequestProperty("Content-Type",
                          "multipart/form-data;boundary="+boundary);
       /* 设定DataOutputStream */
       DataOutputStream ds =
         new DataOutputStream(con.getOutputStream());
       ds.writeBytes(twoHyphens + boundary + end);
       ds.writeBytes("Content-Disposition: form-data; " +
                     "name=\"uploadfile\";filename=\"" +
                     newName +"\"" + end);
       ds.writeBytes(end);  

       /* 取得文件的FileInputStream */
       FileInputStream fStream = new FileInputStream(path);
       /* 设定每次写入1024bytes */
       int bufferSize = 1024;
       byte[] buffer = new byte[bufferSize];

       int length = -1;
       /* 从文件读取数据到缓冲区 */
       while((length = fStream.read(buffer)) != -1)
       {
         /* 将数据写入DataOutputStream中 */
         ds.write(buffer, 0, length);
       }
       ds.writeBytes(end);
       ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

       /* close streams */
       fStream.close();
       ds.flush();
       /* 取得Response内容 */
       InputStream is = con.getInputStream();
       int ch;
       StringBuffer b =new StringBuffer();
       while( ( ch = is.read() ) != -1 )
       {
         b.append( (char)ch );
       }
       /* 将Response显示于Dialog */
       showDialog(b.toString().trim());
       /* 关闭DataOutputStream */
       ds.close();
     }
     catch(Exception e)
     {
       showDialog(""+e);
     }
   }
   /* 显示Dialog的method */
   private void showDialog(String mess)
   {
     new AlertDialog.Builder(Pic.this).setTitle("Message")
      .setMessage(mess)
      .setNegativeButton("确定",new DialogInterface.OnClickListener()
      {
        public void onClick(DialogInterface dialog, int which)
        {         
        }
      })
      .show();
   }

    //class

 

pic.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<TextView   
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="@string/hello" 
    /> 
   <Button
     android:id="@+id/bpic"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="鎷嶇収涓婁紶 "
    />
   <Button  
        android:id="@+id/b01" 
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="鏈湴涓婁紶"
    /> 
    <ImageView 
        android:id="@+id/iv01" 
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
     /> 
</LinearLayout> 

 

 android_upload_o.php

<?php
$uploaddir = './data/attachment/forum/201111/23/wwws.jpg';
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploaddir)) {
        echo "<script>alert('上传成功!'); location.href='".$uploaddir."';</script>";
        //echo $uploaddir;
}
else
{
 echo "errors";
}
?>

 

 

  • 0
    点赞
  • 2
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值