android上传文件

服务器采用ssh架构,其实就是一个action
package action;

import java.io.File;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private int result;
	private String msg;
	private String uploadedPictureFileName;
	private File uploadedPicture;

	// --------------------------------------Get And
	// Set--------------------------------------------------//
	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 getUploadedPictureFileName() {
		return uploadedPictureFileName;
	}

	public void setUploadedPictureFileName(String uploadedPictureFileName) {
		this.uploadedPictureFileName = uploadedPictureFileName;
	}

	public File getUploadedPicture() {
		return uploadedPicture;
	}

	public void setUploadedPicture(File uploadedPicture) {
		this.uploadedPicture = uploadedPicture;
	}

	// --------------------------------------Method--------------------------------------------------//
	public String receiveFile() throws Exception {
		File f = new File("f:\\" + getUploadedPictureFileName());
		System.out.println("f:\\" + getUploadedPictureFileName());
		FileUtils.copyFile(getUploadedPicture(), f);
		return null;
	}

}


android端,首先选择一个图片或者录音或者视频,在选择完毕的时候会上传到服务器中。
package cn.upload;

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 android.app.Activity;
import android.content.ContentResolver;
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.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class UploadAppActivity extends Activity {
	private String urlServer = "http://192.168.1.202:8080/aa/user/user!receiveFile.action";
	private String lineEnd = "\r\n";
	private String pathOfPicture;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button button = (Button) findViewById(R.id.b01);
		button.setText("选择图片");
		button.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, 1);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println(requestCode + "=============================");
		if (resultCode == RESULT_OK) {
			Uri uri = data.getData();
			pathOfPicture = getAbsoluteImagePath(uri);
			System.out.println("ok============================="
					+ pathOfPicture);
			Log.e("uri", uri.getHost());
			ContentResolver cr = this.getContentResolver();
			try {
				// 选
				InputStream is = cr.openInputStream(uri);
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				ImageView imageView = (ImageView) findViewById(R.id.iv01);
				imageView.setImageBitmap(bitmap);

				File f = new File(pathOfPicture);
				System.out.println("--------------------------------"
						+ f.exists());

				// 上传服务器
				int bytesAvailable, bufferSize, bytesRead;
				int maxBufferSize = 1 * 1024 * 512;
				byte[] buffer = null;
				String boundary = "---------------------------265001916915724";
				HttpURLConnection connection = null;
				DataOutputStream dos = null;
				FileInputStream fin = null;

				URL url = new URL(urlServer);
				connection = (HttpURLConnection) url.openConnection();
				// 允许向url流中读写数据
				connection.setDoInput(true);
				connection.setDoOutput(true);
				connection.setUseCaches(true);
				// 启动post方法
				connection.setRequestMethod("POST");
				// 设置请求头内容
				connection.setRequestProperty("connection", "Keep-Alive");
				connection.setRequestProperty("Content-Type", "text/plain");
				// 伪造请求头
				connection.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);
				// 开始伪造POST Data里面的数据
				dos = new DataOutputStream(connection.getOutputStream());
				fin = new FileInputStream(pathOfPicture);
				System.out.println("开始上传图片");

				String end = f.getName().substring(
						f.getName().lastIndexOf("."), f.getName().length());
				String bakFile = "1_" + System.currentTimeMillis() + end;
				System.out.println("bakFile:" + bakFile);
				String fileMeta = "--"
						+ boundary
						+ lineEnd
						+ "Content-Disposition: form-data; name=\"uploadedPicture\"; filename=\""
						+ bakFile + "\"" + lineEnd + "Content-Type: image/jpeg"
						+ lineEnd + lineEnd;
				// 向流中写入fileMeta
				dos.write(fileMeta.getBytes());
				// 取得本地图片的字节流,向url流中写入图片字节流
				bytesAvailable = fin.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				buffer = new byte[bufferSize];
				bytesRead = fin.read(buffer, 0, bufferSize);
				while (bytesRead > 0) {
					dos.write(buffer, 0, bufferSize);
					bytesAvailable = fin.available();
					bufferSize = Math.min(bytesAvailable, maxBufferSize);
					bytesRead = fin.read(buffer, 0, bufferSize);
				}
				dos.writeBytes(lineEnd + lineEnd);
				// --------------------伪造images.jpg信息结束-----------------------------------
				// POST Data结束
				dos.writeBytes("--" + boundary + "--");

				// Server端返回的信息
				System.out.println("" + connection.getResponseCode());
				System.out.println("" + connection.getResponseMessage());

				if (dos != null) {
					dos.flush();
					dos.close();
				}
				System.out
						.println("upload success-----------------------------------------");
			} catch (Exception e) {
				Log.e("Exception", e.getMessage());
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	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);
	}
}


附件为android代码,服务器则自己搭建。

你可能感兴趣的:(android)