android上传文件

1.Android端:

1.1 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    
     <TextView
        android:id="@+id/mTextView1" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

      <TextView
        android:id="@+id/mTextView2" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
      
        <Button
        android:id="@+id/mButton1" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
     
</LinearLayout>

1.2 Activity:

package org.yang.android.upload;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidUploadFileActivity extends Activity
{

	private String newName = "linux.jpg";
	// 要上传的本地文件路径
	private String uploadFile = Environment.getExternalStorageDirectory()
			+ "/image/psb.jpg";
	// 上传到服务器的指定位置
	private String actionUrl = "http://172.17.151.54:8090/FinalProject/jsp/androidUploadFile";
	private TextView mTextView1;
	private TextView mTextView2;
	private Button mButton1;
	File file = new File(uploadFile);
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		if ( file.exists() )
		{
			System.out.println("FILE IS EXISTS!!");
		}
		else
		{
			System.out.println("FILE IS NOT EXISTS!!");
		}
		System.out.println("uploadFile is " + uploadFile);
		mTextView1 = (TextView) findViewById(R.id.mTextView1);
		mTextView1.setText("FilePath:/n" + uploadFile);
		mTextView2 = (TextView) findViewById(R.id.mTextView2);
		mTextView2.setText("UploadPath:/n" + actionUrl);
		/* 设定mButton的onClick事件处理 */
		mButton1 = (Button) findViewById(R.id.mButton1);
		mButton1.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				FileUplaodUtil.uploadFile(AndroidUploadFileActivity.this.file, actionUrl);
			}
		});
	}
}

1.2 FileUploadUtil.java文件:

package org.yang.android.upload;

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.MalformedURLException;
import java.net.URL;
import java.util.UUID;

import android.util.Log;

/**
 * 
 * 上传工具类
 * 
 * @author spring sky Email:[email protected] QQ:840950105 MyName:石明政
 */
public class FileUplaodUtil
{
	private static final String TAG = "uploadFile";
	private static final int TIME_OUT = 10 * 1000; // 超时时间
	private static final String CHARSET = "utf-8"; // 设置编码

	/**
	 * android上传文件到服务器
	 * 
	 * @param file
	 *                需要上传的文件
	 * @param RequestURL
	 *                请求的rul
	 * @return 返回响应的内容
	 */
	public static String uploadFile(File file, String RequestURL)
	{
		String result = null;
		String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
		String PREFIX = "--", LINE_END = "\r\n";
		String CONTENT_TYPE = "multipart/form-data"; // 内容类型

		try
		{
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url
					.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET); // 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE
					+ ";boundary=" + BOUNDARY);

			if (file != null)
			{
				/**
				 * 当文件不为空,把文件包装并且上传
				 */
				DataOutputStream dos = new DataOutputStream(
						conn.getOutputStream());
				StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);
				/**
				 * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
				 * filename是文件的名字,包含后缀名的 比如:abc.png
				 */
					
				sb.append("Content-Disposition: form-data; name=\"uploaded\"; filename=\""
						+ file.getName()
						+ "\""
						+ LINE_END);
				sb.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINE_END);
				sb.append(LINE_END);
				dos.write(sb.toString().getBytes());
				InputStream is = new FileInputStream(file);
				byte[] bytes = new byte[1024];
				int len = 0;
				while ((len = is.read(bytes)) != -1)
				{
					dos.write(bytes, 0, len);
				}
				is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
						.getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功 当响应成功,获取响应的流
				 */
				int res = conn.getResponseCode();
				Log.e(TAG, "response code:" + res);
				// if(res==200)
				// {
				Log.e(TAG, "request success");
				InputStream input = conn.getInputStream();
				StringBuffer sb1 = new StringBuffer();
				int ss;
				while ((ss = input.read()) != -1)
				{
					sb1.append((char) ss);
				}
				result = sb1.toString();
				Log.e(TAG, "result : " + result);
				// }
				// else{
				// Log.e(TAG, "request error");
				// }
			}
		} catch (MalformedURLException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return result;
	}
}

2.服务器端:

package org.android.action.file;

import java.io.File;

import org.android.tool.UploadFileTool;
import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class UploadFileAction extends ActionSupport
{
	private static final long serialVersionUID = 1L;
	private int result;
	private String msg;
	private String uploadedFileName;
	private File uploaded;

	
	public int getResult()
	{
		return result;
	}


	public void setResult(int result)
	{
		this.result = result;
	}


	public String getMsg()
	{
		return msg;
	}


	public void setMsg(String msg)
	{
		this.msg = msg;
	}


	public String getUploadedFileName()
	{
		return uploadedFileName;
	}


	public void setUploadedFileName(String uploadedFileName)
	{
		this.uploadedFileName = uploadedFileName;
	}


	public File getUploaded()
	{
		return uploaded;
	}


	public void setUploaded(File uploaded)
	{
		this.uploaded = uploaded;
	}


	// --------------------------------------Method--------------------------------------------------//
	public void receiveFile() throws Exception
	{
		File f = new File("e:\\" + getUploadedFileName());
		System.out.println("e:\\" + getUploadedFileName());
		FileUtils.copyFile(getUploaded(), f);
		System.out.println("UPLOAD SUCCESS!!!!!! + Java Web");
	}

}


你可能感兴趣的:(android上传文件)