基本信息
源码名称:android 拍照后将照片即时上传到公网服务器(亲测通过),实例源码下载
源码大小:0.06M
文件格式:.zip
开发语言:Java
更新时间:2013-02-05
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

android拍照后上传照片至服务器,源码中的公网地址改成自己的网站网址即可

private String actionUrl="http://192.168.0.177:8077/test/upload";


android客户端代码:

 

package camera.core.pps;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

//import com.android.project.PhontoActivity;
//import com.android.internal..R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class CameraAndUploadActivity extends Activity {
	
	  /* 变量声明
	   * newName:上传后在服务器上的文件名称
	   * uploadFile:要上传的文件路径
	   * actionUrl:吱服器勺对应的程序路径 */
	  private String newName="image.jpg";
	  private String uploadFile="/data/data/irdc.ex08_11/image.jpg";
	  //private String actionUrl="http://10.10.100.33/upload/upload.jsp";
	  private String actionUrl="http://192.168.0.177:8077/test/upload";
	  
	  
	  
	  //下面是图片处理参数
		private ImageView iv_image;

		private Button bt_camera;

		private Bitmap photo;

		private File file;

		private String saveDir = Environment.getExternalStorageDirectory()
				.getPath()   "/temp_image";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    	iv_image = (ImageView) findViewById(R.id.iv_image);
		bt_camera = (Button) findViewById(R.id.bt_camera);

		bt_camera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				destoryImage();
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					file = new File(saveDir, "temp.jpg");
					file.delete();
					if (!file.exists()) {
						try {
							file.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
							Toast.makeText(CameraAndUploadActivity.this, "照片创建失败!",
									Toast.LENGTH_LONG).show();
							return;
						}
					}
					Intent intent = new Intent(
							"android.media.action.IMAGE_CAPTURE");
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
					startActivityForResult(intent, 1);
				} else {
					Toast.makeText(CameraAndUploadActivity.this, "sdcard无效或没有插入!",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		File savePath = new File(saveDir);
		if (!savePath.exists()) {
			savePath.mkdirs();
		}
        
    }
    
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == RESULT_OK) {
			if (file != null && file.exists()) {
				BitmapFactory.Options option = new BitmapFactory.Options();
				option.inSampleSize = 2;
				photo = BitmapFactory.decodeFile(file.getPath(), option);
				iv_image.setImageBitmap(photo);
				
				uploadFile=file.getPath();
				uploadFile();
			}
		}
	}

	@Override
	protected void onDestroy() {
		destoryImage();
		super.onDestroy();
	}

	private void destoryImage() {
		if (photo != null) {
			photo.recycle();
			photo = null;
		}
	}
    
    
    /* 上传文件吹Server的method */
    private void uploadFile()
    {
      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=\"file1\";filename=\""  
                      newName  "\""   end);
        ds.writeBytes(end);   

        /* 取得文件的FileInputStream */
        FileInputStream fStream = new FileInputStream(uploadFile);
        /* 设定每次写入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(CameraAndUploadActivity.this).setTitle("Message")
       .setMessage(mess)
       .setNegativeButton("确定",new DialogInterface.OnClickListener()
       {
         public void onClick(DialogInterface dialog, int which)
         {          
         }
       })
       .show();
    }
    
}

服务器端C#代码:

        [HttpPost]
        public ContentResult Upload(HttpPostedFileBase file1)
        {

            #region 上传图片
            var target = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<Kt.Framework.FileServer.IImageFile>();

            var fileKey = target.SaveImageFile(file1.InputStream, file1.FileName);
            var key = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<Kt.Framework.FileServer.IKey>();
            var fileUrl = key.GetFileUrl(fileKey);
            #endregion


            var cc = new ContentResult();
            cc.Content = fileUrl;
            return cc;
        }