android 上传图片 客户端与 服务端 方案总结 (包括获取当前的进度)

本文介绍了一种使用Android客户端上传图片到服务器的方法,并提供了一个带有进度条的上传示例。包括客户端和服务端的代码实现,涉及HTTP请求、Base64编码、多线程通信等关键技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种:

       客户端:

        

package com.hexiaochun;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.hexiaochun.utils.Base64Coder;
import com.hexiaochun.utils.ZoomBitmap;

import android.app.Activity;
import android.app.ProgressDialog;
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.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener {
	//http://192.168.23.1:8080/test/receiverData
	// 服务器地址http://172.16.204.24:8080/ImageServer/upServer
	private static final String HOST = "http://172.16.204.24:8080/ImageServer/upServer";
	// 显示图片
	private ImageView image;
	// 两个but
	private Button take;
	private Button selete;
	// 记录文件名
	private String filename;
	// 上传的bitmap
	private Bitmap upbitmap;
	private Button up;
	
	//多线程通信
	private Handler myHandler;
	private ProgressDialog myDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		image = (ImageView) this.findViewById(R.id.imageView1);
		take = (Button) this.findViewById(R.id.take);
		selete = (Button) this.findViewById(R.id.selete);
		up=(Button)this.findViewById(R.id.up);
		take.setOnClickListener(this);
		selete.setOnClickListener(this);
		up.setOnClickListener(this);

		myHandler=new MyHandler();
	}

	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.take:
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			filename = "xiaochun" + System.currentTimeMillis() + ".jpg";
			System.out.println(filename);
			// 下面这句指定调用相机拍照后的照片存储的路径
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
					Environment.getExternalStorageDirectory(), filename)));
			startActivityForResult(intent, 1);
			break;
		case R.id.selete:
			intent = new Intent(Intent.ACTION_PICK, null);
			intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
					"image/*");
			startActivityForResult(intent, 2);
			break;
		case R.id.up:
			myDialog = ProgressDialog.show(this, "Loading...", "Please wait...", true, false);
			new Thread(new Runnable() {
				public void run() {
					upload();
					myHandler.sendMessage(new Message());
				}
			}).start();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
		switch (requestCode) {
		case 1:
			//解成bitmap,方便裁剪
			Bitmap bitmap=BitmapFactory.decodeFile(Environment.
					getExternalStorageDirectory().getPath()+"/"+filename);
			float wight=bitmap.getWidth();
			float height=bitmap.getHeight();
//			ZoomBitmap.zoomImage(bitmap, wight/8, height/8);
			image.setImageBitmap(ZoomBitmap.zoomImage(bitmap, wight/8, height/8));
			upbitmap=ZoomBitmap.zoomImage(bitmap, wight/8, height/8);
			break;
		case 2:
			if(data!=null){
				image.setImageURI(data.getData());
				System.out.println(getAbsoluteImagePath(data.getData()));
				upbitmap=BitmapFactory.decodeFile(getAbsoluteImagePath(data.getData()));
				//剪一下,防止测试的时候上传的文件太大
				upbitmap=ZoomBitmap.zoomImage(upbitmap, upbitmap.getWidth()/8, upbitmap.getHeight()/8);
			}
			break;
		default:
			break;
		}
	}

	// 取到绝对路径
	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);
	}

	// 上传
	public void upload() {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		upbitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
		byte[] b = stream.toByteArray();
		// 将图片流以字符串形式存储下来
		String file = new String(Base64Coder.encodeLines(b));
		HttpClient client = new DefaultHttpClient();
		// 设置上传参数
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("file", file));
		HttpPost post = new HttpPost(HOST);
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(formparams, "UTF-8");
			post.addHeader("Accept",
					"text/javascript, text/html, application/xml, text/xml");
			post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
			post.addHeader("Accept-Encoding", "gzip,deflate,sdch");
			post.addHeader("Connection", "Keep-Alive");
			post.addHeader("Cache-Control", "no-cache");
			post.addHeader("Content-Type", "application/x-www-form-urlencoded");
			post.setEntity(entity);
			HttpResponse response = client.execute(post);
			System.out.println(response.getStatusLine().getStatusCode());
			HttpEntity e = response.getEntity();
			System.out.println(EntityUtils.toString(e));
			if (200 == response.getStatusLine().getStatusCode()) {
				System.out.println("上传完成");
			} else {
				System.out.println("上传失败");
			}
			client.getConnectionManager().shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private class MyHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			myDialog.dismiss();
		}
	}

}
工具类:

package com.hexiaochun.utils;




/**
 * 下面这些注释是下载这个类的时候本来就有的,本来要删除的,但看了下竟然是license,吼吼,
 * 好东西,留在注释里,以备不时之用,大家有需要加license的可以到下面的网址找哦
 */

//EPL, Eclipse Public License, V1.0 or later, http://www.eclipse.org/legal
//LGPL, GNU Lesser General Public License, V2.1 or later, http://www.gnu.org/licenses/lgpl.html
//GPL, GNU General Public License, V2 or later, http://www.gnu.org/licenses/gpl.html
//AL, Apache License, V2.0 or later, http://www.apache.org/licenses
//BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php
/**
* A Base64 encoder/decoder.
*
* <p>
* This class is used to encode and decode data in Base64 format as described in RFC 1521.
*
* <p>
* Project home page: <a href="http://www.source-code.biz/base64coder/java/">www.source-code.biz/base64coder/java</a><br>
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
* Multi-licensed: EPL / LGPL / GPL / AL / BSD.
*/

/**
 * 这个类在上面注释的网址中有,大家可以自行下载下,也可以直接用这个,
 * 公开的Base64Coder类(不用深究它是怎么实现的,
 * 还是那句话,有轮子直接用轮子),好用的要死人了...
 * 小马也很无耻的引用了这个网址下的东东,吼吼...
* @Title: Base64Coder.java
* @Package com.xiaoma.piccut.demo
* @Description: TODO
* @author XiaoMa
 */

public class Base64Coder {

//The line separator string of the operating system.
private static final String systemLineSeparator = System.getProperty("line.separator");

//Mapping table from 6-bit nibbles to Base64 characters.
private static char[]    map1 = new char[64];
static {
   int i=0;
   for (char c='A'; c<='Z'; c++) map1[i++] = c;
   for (char c='a'; c<='z'; c++) map1[i++] = c;
   for (char c='0'; c<='9'; c++) map1[i++] = c;
   map1[i++] = '+'; map1[i++] = '/'; }

//Mapping table from Base64 characters to 6-bit nibbles.
private static byte[]    map2 = new byte[128];
static {
   for (int i=0; i<map2.length; i++) map2[i] = -1;
   for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; }

/**
* Encodes a string into Base64 format.
* No blanks or line breaks are inserted.
* @param s  A String to be encoded.
* @return   A String containing the Base64 encoded data.
*/
public static String encodeString (String s) {
return new String(encode(s.getBytes())); }

/**
* Encodes a byte array into Base 64 format and breaks the output into lines of 76 characters.
* This method is compatible with <code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>.
* @param in  An array containing the data bytes to be encoded.
* @return    A String containing the Base64 encoded data, broken into lines.
*/
public static String encodeLines (byte[] in) {
return encodeLines(in, 0, in.length, 76, systemLineSeparator); }

/**
* Encodes a byte array into Base 64 format and breaks the output into lines.
* @param in            An array containing the data bytes to be encoded.
* @param iOff          Offset of the first byte in <code>in</code> to be processed.
* @param iLen          Number of bytes to be processed in <code>in</code>, starting at <code>iOff</code>.
* @param lineLen       Line length for the output data. Should be a multiple of 4.
* @param lineSeparator The line separator to be used to separate the output lines.
* @return              A String containing the Base64 encoded data, broken into lines.
*/
public static String encodeLines (byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) {
int blockLen = (lineLen*3) / 4;
if (blockLen <= 0) throw new IllegalArgumentException();
int lines = (iLen+blockLen-1) / blockLen;
int bufLen = ((iLen+2)/3)*4 + lines*lineSeparator.length();
StringBuilder buf = new StringBuilder(bufLen);
int ip = 0;
while (ip < iLen) {
   int l = Math.min(iLen-ip, blockLen);
   buf.append (encode(in, iOff+ip, l));
   buf.append (lineSeparator);
   ip += l; }
return buf.toString(); }

/**
* Encodes a byte array into Base64 format.
* No blanks or line breaks are inserted in the output.
* @param in  An array containing the data bytes to be encoded.
* @return    A character array containing the Base64 encoded data.
*/
public static char[] encode (byte[] in) {
return encode(in, 0, in.length); }

/**
* Encodes a byte array into Base64 format.
* No blanks or line breaks are inserted in the output.
* @param in    An array containing the data bytes to be encoded.
* @param iLen  Number of bytes to process in <code>in</code>.
* @return      A character array containing the Base64 encoded data.
*/
public static char[] encode (byte[] in, int iLen) {
return encode(in, 0, iLen); }

/**
* Encodes a byte array into Base64 format.
* No blanks or line breaks are inserted in the output.
* @param in    An array containing the data bytes to be encoded.
* @param iOff  Offset of the first byte in <code>in</code> to be processed.
* @param iLen  Number of bytes to process in <code>in</code>, starting at <code>iOff</code>.
* @return      A character array containing the Base64 encoded data.
*/
public static char[] encode (byte[] in, int iOff, int iLen) {
int oDataLen = (iLen*4+2)/3;       // output length without padding
int oLen = ((iLen+2)/3)*4;         // output length including padding
char[] out = new char[oLen];
int ip = iOff;
int iEnd = iOff + iLen;
int op = 0;
while (ip < iEnd) {
   int i0 = in[ip++] & 0xff;
   int i1 = ip < iEnd ? in[ip++] & 0xff : 0;
   int i2 = ip < iEnd ? in[ip++] & 0xff : 0;
   int o0 = i0 >>> 2;
   int o1 = ((i0 &   3) << 4) | (i1 >>> 4);
   int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
   int o3 = i2 & 0x3F;
   out[op++] = map1[o0];
   out[op++] = map1[o1];
   out[op] = op < oDataLen ? map1[o2] : '='; op++;
   out[op] = op < oDataLen ? map1[o3] : '='; op++; }
return out; }

/**
* Decodes a string from Base64 format.
* No blanks or line breaks are allowed within the Base64 encoded input data.
* @param s  A Base64 String to be decoded.
* @return   A String containing the decoded data.
* @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
*/
public static String decodeString (String s) {
return new String(decode(s)); }

/**
* Decodes a byte array from Base64 format and ignores line separators, tabs and blanks.
* CR, LF, Tab and Space characters are ignored in the input data.
* This method is compatible with <code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>.
* @param s  A Base64 String to be decoded.
* @return   An array containing the decoded data bytes.
* @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
*/
public static byte[] decodeLines (String s) {
char[] buf = new char[s.length()+3];
int p = 0;
for (int ip = 0; ip < s.length(); ip++) {
   char c = s.charAt(ip);
   if (c != ' ' && c != '\r' && c != '\n' && c != '\t')
      buf[p++] = c; }
   while ((p % 4) != 0)
	   buf[p++] = '0';
	
return decode(buf, 0, p); }

/**
* Decodes a byte array from Base64 format.
* No blanks or line breaks are allowed within the Base64 encoded input data.
* @param s  A Base64 String to be decoded.
* @return   An array containing the decoded data bytes.
* @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
*/
public static byte[] decode (String s) {
return decode(s.toCharArray()); }

/**
* Decodes a byte array from Base64 format.
* No blanks or line breaks are allowed within the Base64 encoded input data.
* @param in  A character array containing the Base64 encoded data.
* @return    An array containing the decoded data bytes.
* @throws    IllegalArgumentException If the input is not valid Base64 encoded data.
*/
public static byte[] decode (char[] in) {
return decode(in, 0, in.length); }

/**
* Decodes a byte array from Base64 format.
* No blanks or line breaks are allowed within the Base64 encoded input data.
* @param in    A character array containing the Base64 encoded data.
* @param iOff  Offset of the first character in <code>in</code> to be processed.
* @param iLen  Number of characters to process in <code>in</code>, starting at <code>iOff</code>.
* @return      An array containing the decoded data bytes.
* @throws      IllegalArgumentException If the input is not valid Base64 encoded data.
*/
public static byte[] decode (char[] in, int iOff, int iLen) {
if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
while (iLen > 0 && in[iOff+iLen-1] == '=') iLen--;
int oLen = (iLen*3) / 4;
byte[] out = new byte[oLen];
int ip = iOff;
int iEnd = iOff + iLen;
int op = 0;
while (ip < iEnd) {
   int i0 = in[ip++];
   int i1 = in[ip++];
   int i2 = ip < iEnd ? in[ip++] : 'A';
   int i3 = ip < iEnd ? in[ip++] : 'A';
   if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
      throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
   int b0 = map2[i0];
   int b1 = map2[i1];
   int b2 = map2[i2];
   int b3 = map2[i3];
   if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
      throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
   int o0 = ( b0       <<2) | (b1>>>4);
   int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
   int o2 = ((b2 &   3)<<6) |  b3;
   out[op++] = (byte)o0;
   if (op<oLen) out[op++] = (byte)o1;
   if (op<oLen) out[op++] = (byte)o2; }
return out; }

//Dummy constructor.
private Base64Coder() {}

} // end class Base64Coder

package com.hexiaochun.utils;

import android.graphics.Bitmap;
import android.graphics.Matrix;

public class ZoomBitmap {

	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}
}

客户端所引用的包 httpclient-4.1.3,httpcore-4.1.4

 服务器端servlet --

  

package com.hexiaochun;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hexiaochun.utils.Base64Coder;


public class UpServer extends HttpServlet {

	private String file;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
//		super.doPost(req, resp);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("upload........");
		file=req.getParameter("file");
		if(file!=null){
			System.out.println("up.ing ");
			byte[] b= Base64Coder.decodeLines(file);
			String filepath=req.getSession().getServletContext().getRealPath("/files");
			File file=new File(filepath);
			if(!file.exists())
				file.mkdirs();
			FileOutputStream fos=new FileOutputStream(file.getPath()+"/person_head"+(int)(Math.random()*100)+".png");
			System.out.println(file.getPath());
			fos.write(b);
			fos.flush();
			fos.close();
		}
	}

	

}


第二种带进度条的上传方式


客户端:  需要引入 httpmime-4.1.2.jar

 代码示例:

  主页面:

   

package com.lxb.uploadwithprogress;

import java.io.File;

import com.lxb.uploadwithprogress.http.HttpMultipartPost;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	
	private Context context;
	
	private EditText et_filepath;
	private Button btn_upload;
	private Button btn_cancle;
	
	private HttpMultipartPost post;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        context = this;
        
        setContentView(R.layout.activity_main);
        
        et_filepath = (EditText) findViewById(R.id.et_filepath);
        File storageDirectory = Environment.getExternalStorageDirectory();
       String path= storageDirectory.getAbsolutePath()+"/testImage/01.jpg";
        et_filepath.setText(path);
        btn_upload = (Button) findViewById(R.id.btn_upload);
        btn_cancle = (Button) findViewById(R.id.btn_cancle);
     
        btn_upload.setOnClickListener(this);
        btn_cancle.setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_upload:
			String filePath = et_filepath.getText().toString();
			File file = new File(filePath);
			if (file.exists()) {
				post = new HttpMultipartPost(context, filePath);
				post.execute();
			} else {
				Toast.makeText(context, "file not exists", Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.btn_cancle:
			if (post != null) {
				if (!post.isCancelled()) {
					post.cancel(true);
				}
			}
			break;
		}
		
	}
    
}

自定义的CustomMultipartEntity

package com.lxb.uploadwithprogress.http;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;

public class CustomMultipartEntity extends MultipartEntity {

	private final ProgressListener listener;

	public CustomMultipartEntity(final ProgressListener listener) {
		super();
		this.listener = listener;
	}

	public CustomMultipartEntity(final HttpMultipartMode mode,
			final ProgressListener listener) {
		super(mode);
		this.listener = listener;
	}

	public CustomMultipartEntity(HttpMultipartMode mode, final String boundary,
			final Charset charset, final ProgressListener listener) {
		super(mode, boundary, charset);
		this.listener = listener;
	}

	@Override
	public void writeTo(OutputStream outstream) throws IOException {
		super.writeTo(new CountingOutputStream(outstream, this.listener));
	}

	public static interface ProgressListener {
		void transferred(long num);
	}

	public static class CountingOutputStream extends FilterOutputStream {
		
		private final ProgressListener listener;
		private long transferred;

		public CountingOutputStream(final OutputStream out,
				final ProgressListener listener) {
			super(out);
			this.listener = listener;
			this.transferred = 0;
		}

		public void write(byte[] b, int off, int len) throws IOException {
			out.write(b, off, len);
			this.transferred += len;
			this.listener.transferred(this.transferred);
		}

		public void write(int b) throws IOException {
			out.write(b);
			this.transferred++;
			this.listener.transferred(this.transferred);
		}
	}

}

package com.lxb.uploadwithprogress.http;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.lxb.uploadwithprogress.http.CustomMultipartEntity.ProgressListener;

public class HttpMultipartPost extends AsyncTask<String, Integer, String> {

	private Context context;
	private String filePath;
	private ProgressDialog pd;
	private long totalSize;

	public HttpMultipartPost(Context context, String filePath) {
		this.context = context;
		this.filePath = filePath;
	}

	@Override
	protected void onPreExecute() {
		pd = new ProgressDialog(context);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("Uploading Picture...");
		pd.setCancelable(false);
		pd.show();
	}

	@Override
	protected String doInBackground(String... params) {
		String serverResponse = null;

		HttpClient httpClient = new DefaultHttpClient();
		HttpContext httpContext = new BasicHttpContext();

		HttpPost httpPost = new HttpPost("http://172.16.204.24:8080/web2/LoginServlet");

		try {
			CustomMultipartEntity multipartContent = new CustomMultipartEntity(
					new ProgressListener() {
						@Override
						public void transferred(long num) {
							publishProgress((int) ((num / (float) totalSize) * 100));
						}
					}); 
			// We use FileBody to transfer an image
			multipartContent.addPart("data", new FileBody(new File(
					filePath)));
			
			totalSize = multipartContent.getContentLength();

			// Send it
			httpPost.setEntity(multipartContent);
			HttpResponse response = httpClient.execute(httpPost, httpContext);
			serverResponse = EntityUtils.toString(response.getEntity());
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return serverResponse;
	}

	@Override
	protected void onProgressUpdate(Integer... progress) {
		pd.setProgress((int) (progress[0]));
	}

	@Override
	protected void onPostExecute(String result) {
		System.out.println("result: " + result);
		pd.dismiss();
	}

	@Override
	protected void onCancelled() {
		System.out.println("cancle");
	}

}


后台示例:

  后台servlet 需要引入jar commons-fileupload-1.2.2.jar 和 commons-io-2.0.1.jar   这里只关注doPost 方法就好

   

package cn.itcast.web;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// request.getParameter () ���������˵�iso8850-1 ��ʽ�õ���string 
		String name = request.getParameter("name");
		if(name!=null){
		    name =	new String( name.getBytes("iso8859-1"),"utf-8");
		    
		}
		
		String password = request.getParameter("password");
		System.out.println(name);
		System.out.println(password);
		
		if("zhangsan".equals(name)&&"123456".equals(password)){
			response.getOutputStream().write("login succes".getBytes());
		}else{
			response.getOutputStream().write("login failed".getBytes());
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//doGet(request, response);
		// ����������ϴ����ļ� 
		System.out.println("dopost...........");
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(isMultipart){
			String realpath = request.getSession().getServletContext().getRealPath("/files");
			System.out.println(realpath);
			File dir = new File(realpath);
			if(!dir.exists()) dir.mkdirs();
			
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			try {
				List<FileItem> items = upload.parseRequest(request);
				for(FileItem item : items){
					if(item.isFormField()){
						 String name1 = item.getFieldName();//�õ������������
						 String value = item.getString("UTF-8");//�õ�����ֵ
						 System.out.println(name1+ "="+ value);
					}else{
						item.write(new File(dir, System.currentTimeMillis()+ item.getName().substring(item.getName().lastIndexOf("."))));
					}
				}
			
			response.getOutputStream().write("你好".getBytes("iso-8859-1"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			doGet(request, response);
		}
		
	}

}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值