码迷,mamicode.com
首页 > 移动开发 > 详细

android上传文件到wamp服务器

时间:2015-04-25 14:52:21      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:

1.php server(wamp)部分

建立unload.php页面代码如下

<?php

move_uploaded_file($_FILES["file1"]["tmp_name"],
      "upload/" . $_FILES["file1"]["name"]);
      echo "存储在: " . "upload/" . $_FILES["file1"]["name"];	  
?> 

  

需要配置c:\windows\temp的目录权限,user group有权限写

技术分享


另外ip访问设置,wamp中的c:\wamp\alias\adt.conf
添加Allow from 192.168.0.102 指定IP

 

2.android部分

Main.java

package com.test;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
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.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {
	/*
	 * 变量声明 newName:上传后在服务器上的文件名称 uploadFile:要上传的文件路径 actionUrl:服务器上对应的程序路径
	 */
	private String newName = "pp.jpg";
	private String uploadFile = "/data/pp.jpg";
	private String actionUrl = "http://192.168.0.102/tp/upload.php";
	private TextView mText1;
	private TextView mText2;
	private Button mButton;
	private String msg_result = null;
	public static final int REFRESH = 0x000001;
	private static final int FILE_SELECT_CODE = 1 ;
	protected static final int PROGRESS_VISIBLE = 10;
	protected static final int PROGRESS_INVISIBLE = 11;	
	private Handler mHandler = null;
	
	private ProgressBar progressBar1 = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		progressBar1 = (ProgressBar)findViewById(R.id.progress_horizontal);
		
		mText1 = (TextView) findViewById(R.id.myText2);
		mText1.setText("文件路径:\n" + uploadFile);
		mText2 = (TextView) findViewById(R.id.myText3);
		mText2.setText("上传网址:\n" + actionUrl);
		/* 设置mButton的onClick事件处理 */
		mButton = (Button) findViewById(R.id.myButton);
		mButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//showFileChooser();
				File f = new File(uploadFile);
				if (!f.exists()) {
					showDialog(uploadFile + "\r\n文件不存在");
					return;
				}
				new MyThread().start();
			}
		});
		
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == REFRESH) {

					showDialog(msg_result); 
				}
				else if (msg.what == PROGRESS_VISIBLE){
					progressBar1.setVisibility(View.VISIBLE);			
				}
				else if (msg.what == PROGRESS_INVISIBLE){
					progressBar1.setVisibility(View.INVISIBLE);			
				}
				super.handleMessage(msg);
			}
		};
	}

	/* 上传文件至Server的方法 */
	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;
			/* 从文件读取数据至缓冲区 */
			int sum = 0;
			
			Message msg = new Message();
			msg.what = PROGRESS_VISIBLE;
			mHandler.sendMessage(msg);					
			while ((length = fStream.read(buffer)) != -1) {
				sum += length;			
				/* 将资料写入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();		
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
			byte[] by = new byte[1000];
			int n = 0;
			while ((n = is.read(by)) != -1) {  
                bos.write(by, 0, n);  
            }  
			
			
			msg_result = bos.toString();
			/* 关闭DataOutputStream */
			ds.close();
			
			msg = new Message();
			msg.what = PROGRESS_INVISIBLE;
			mHandler.sendMessage(msg);
			
		} catch (Exception e) {
			msg_result = e.getMessage();			
		}
	}

	/* 显示Dialog的method */
	private void showDialog(String mess) {
		new AlertDialog.Builder(Main.this).setTitle("Message1")
				.setMessage(mess)
				.setNegativeButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).show();
	}
	
	
	public class MyThread extends Thread {
		public void run() {
			uploadFile();
			Message msg = new Message();
			msg.what = REFRESH;
			mHandler.sendMessage(msg);
		}
	}
}

layout的main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
  android:id="@+id/layout1"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@drawable/white"
  xmlns:android="http://schemas.android.com/apk/res/android"
>
  <TextView
    android:id="@+id/myText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/str_title"
    android:textSize="20sp"
    android:textColor="@drawable/black"
    android:layout_x="10px"
    android:layout_y="12px"
  >
  </TextView>
  <TextView
    android:id="@+id/myText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:textColor="@drawable/black"
    android:layout_x="10px"
    android:layout_y="52px"
  >
  </TextView>
  <TextView
    android:id="@+id/myText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:textColor="@drawable/black"
    android:layout_x="10px"
    android:layout_y="102px"
  >
  </TextView>
  <Button
    android:id="@+id/myButton"
    android:layout_width="92px"
    android:layout_height="49px"
    android:text="@string/str_button"
    android:textSize="15sp"
    android:layout_x="90px"
    android:layout_y="170px"
  >
  </Button>
  
     <ProgressBar
         android:id="@+id/progress_horizontal"
         android:layout_width="292px"
         android:layout_height="49px"
         android:layout_x="90px"
         android:layout_y="250px"
         android:max="100"
         android:progress="0"
         android:secondaryProgress="0"
         android:visibility="invisible" />

</AbsoluteLayout>

  

AndroidManifest.xml需要添加权限

 <uses-permission android:name="android.permission.INTERNET" />

 

 

事例

技术分享技术分享

 

android上传文件到wamp服务器

标签:

原文地址:http://www.cnblogs.com/coolyylu/p/4455845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!