两种android客户端传图片的方法

///////////2016/03/14///////////

/////////by  xbw/////////////////

/////////环境 eclipse php//


第一种,‘

一个类FileUtil

package com.example.image_head;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;

public class FileUtil {

   
	public static String saveFile(Context c, String fileName, Bitmap bitmap) {
		return saveFile(c, "", fileName, bitmap);
	}
	
	public static String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) {
		byte[] bytes = bitmapToBytes(bitmap);
		return saveFile(c, filePath, fileName, bytes);
	}
	
	public static byte[] bitmapToBytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(CompressFormat.JPEG, 100, baos);
		return baos.toByteArray();
	}
	
	public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) {
		String fileFullName = "";
		FileOutputStream fos = null;
		String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA)
				.format(new Date());
		try {
			String suffix = "";
			if (filePath == null || filePath.trim().length() == 0) {
				filePath = Environment.getExternalStorageDirectory() + "/JiaXT/" + dateFolder + "/";
			}
			File file = new File(filePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			File fullFile = new File(filePath, fileName + suffix);
			fileFullName = fullFile.getPath();
			fos = new FileOutputStream(new File(filePath, fileName + suffix));
			fos.write(bytes);
		} catch (Exception e) {
			fileFullName = "";
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					fileFullName = "";
				}
			}
		}
		return fileFullName;
	}
}

第二个类 NetUtil

package com.example.image_head;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class NetUtil {

	// 一般来说用一个生成一个UUID的话,会可靠很多,这里就不考虑这个了
	// 而且一般来说上传文件最好用BASE64进行编码,你只要用BASE64不用的符号就可以保证不冲突了。
	// 尤其是上传二进制文件时,其中很可能有\r、\n之类的控制字符,有时还可能出现最高位被错误处理的问题,所以必须进行编码。 
	public static final String BOUNDARY = "--my_boundary--";

	/**
	 * 普通字符串数据
	 * @param textParams
	 * @param ds
	 * @throws Exception
	 */
	public static void writeStringParams(Map<String, String> textParams,
			DataOutputStream ds) throws Exception {
		Set<String> keySet = textParams.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String name = it.next();
			String value = textParams.get(name);
			ds.writeBytes("--" + BOUNDARY + "\r\n");
			ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
			ds.writeBytes("\r\n");
			value = value + "\r\n";
			ds.write(value.getBytes());

		}
	}

	/**
	 * 文件数据
	 * @param fileparams
	 * @param ds
	 * @throws Exception
	 */
	public static void writeFileParams(Map<String, File> fileparams, 
			DataOutputStream ds) throws Exception {
		Set<String> keySet = fileparams.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String name = it.next();
			File value = fileparams.get(name);
			ds.writeBytes("--" + BOUNDARY + "\r\n");
			//uploadedfile与服务器端内容匹配
			ds.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
					+ URLEncoder.encode(value.getName(), "UTF-8") + "\"\r\n");
			ds.writeBytes("Content-Type:application/octet-stream \r\n");
			ds.writeBytes("\r\n");
			ds.write(getBytes(value));
			ds.writeBytes("\r\n");
		}
	}

	// 把文件转换成字节数组
	private static byte[] getBytes(File f) throws Exception {
		FileInputStream in = new FileInputStream(f);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int n;
		while ((n = in.read(b)) != -1) {
			out.write(b, 0, n);
		}
		in.close();
		return out.toByteArray();
	}

	/**
	 * 添加结尾数据
	 * @param ds
	 * @throws Exception
	 */
	public static void paramsEnd(DataOutputStream ds) throws Exception {
		ds.writeBytes("--" + BOUNDARY + "--" + "\r\n");
		ds.writeBytes("\r\n");
	}

	public static String readString(InputStream is) {
		return new String(readBytes(is));
	}

	public static byte[] readBytes(InputStream is) {
		try {
			byte[] buffer = new byte[1024];
			int len = -1;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while ((len = is.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			baos.close();
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}


方法,在button的点击事件中添加线程

new Thread(uploadImageRunnable).start();

Runnable uploadImageRunnable = new Runnable() {
			@Override
			public void run() {
				if(TextUtils.isEmpty(imgUrl)){//php服务器端url
					Toast.makeText(getActivity(), "还没有设置上传服务器的路径!", Toast.LENGTH_SHORT).show();
					return;
				}
				Map<String, String> textParams = new HashMap<String, String>();
				Map<String, File> fileparams = new HashMap<String, File>();
				try {
					// 创建一个URL对象
					URL url = new URL(imgUrl);
					textParams = new HashMap<String, String>();
					fileparams = new HashMap<String, File>();
					// 要上传的图片文件
					File file = new File(urlpath);//本地图片路径
					fileparams.put("image", file);
					// 利用HttpURLConnection对象从网络中获取网页数据
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					// 设置连接超时(记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作)
					conn.setConnectTimeout(5000);
					// 设置允许输出(发送POST请求必须设置允许输出)
					conn.setDoOutput(true);
					// 设置使用POST的方式发送
					conn.setRequestMethod("POST");
					// 设置不使用缓存(容易出现问题)
					conn.setUseCaches(false);
					conn.setRequestProperty("Charset", "UTF-8");//设置编码   
					// 在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头
					conn.setRequestProperty("ser-Agent", "Fiddler");
					// 设置contentType
					conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + NetUtil.BOUNDARY);
					OutputStream os = conn.getOutputStream();
					DataOutputStream ds = new DataOutputStream(os);
					NetUtil.writeStringParams(textParams, ds);
					NetUtil.writeFileParams(fileparams, ds);
					NetUtil.paramsEnd(ds);
					// 对文件流操作完,要记得及时关闭
					os.close();
					// 服务器返回的响应吗
					int code = conn.getResponseCode(); // 从Internet获取网页,发送请求,将网页以流的形式读回来
					// 对响应码进行判断
					if (code == 200) {// 返回的响应码200,是成功
						// 得到网络返回的输入流
						InputStream is = conn.getInputStream();
						resultStr = NetUtil.readString(is);
					} else {
						Toast.makeText(getActivity(), "请求URL失败!", Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
			}
		};
 
  
Handler handler = new Handler(new Handler.Callback() {
   @Override
   public boolean handleMessage(Message msg) {
    switch (msg.what) {
    case 0:
     //dialogs.dismiss();
     try {
      // 返回数据示例,根据需求和后台数据灵活处理
     
      JSONObject jsonObject = new JSONObject(resultStr);
       String imageUrl = jsonObject.optString("imageUrl");
       Toast.makeText(getActivity(), imageUrl, Toast.LENGTH_SHORT).show();
      }else{
       Toast.makeText(getActivity(), jsonObject.optString("statusMessage"), Toast.LENGTH_SHORT).show();
      }
      
     } catch (JSONException e) {
      e.printStackTrace();
     }
     
     break;
     
    default:
     break;
    }
    return false;
   }
  });

这样就好了


第二种。

在button监听事件中添加

new Task().execute();

class Task extends AsyncTask<String, Integer, Integer> {

			@Override
			protected Integer doInBackground(String... strings) {
				Integer result = -1;
				try {
					result = UpFile.post(config_a.uploadUrl,
					 new File("/storage/extSdCard/b.png"));//本地图片路径
				}
				catch (IOException e) {
					e.printStackTrace();
				}
				return result;
			}
			@Override
			protected void onPostExecute(Integer result) {
				Toast.makeText(getActivity(), "" + result, Toast.LENGTH_LONG).show();
			}
		}

Upload_image.java类
package com.example.image_head;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import com.example.configs.config_a;

import android.widget.Toast;

public class Upload_image {

	public static class UpFile {
		public static  int post(String actionUrl, File file) throws IOException {
			//产生随机分隔内容
			String BOUNDARY = UUID.randomUUID().toString();
			String PREFIX = "--";
			String LINEND = "\r\n";
			String MULTIPART_FROM_DATA = "multipart/form-data";
			String CHARSET = "UTF-8";
			URL url = new URL(actionUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//设置超时时间单位是毫秒
			conn.setReadTimeout(5 * 1000);
			//设置允许输入
			conn.setDoInput(true);
			//设置允许输出
			conn.setDoOutput(true);
			//不允许使用缓存
			conn.setUseCaches(false);
			//设置请求的方法为Post
			conn.setRequestMethod("POST");
			//设置维持长连接
			conn.setRequestProperty("Connection", "keep-alive");
			//设置字符集为UTF-8
			conn.setRequestProperty("Charset", CHARSET);
			//设置文件的类型
			conn.setRequestProperty("Content-type", MULTIPART_FROM_DATA + "; boundary=" + BOUNDARY);
			DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
			//发送文件数据
			if (file != null) {
				StringBuilder sb = new StringBuilder();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINEND);
				//uploadedfile与服务器端内容匹配
				sb.append("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + file.getName() + "\"" + LINEND);
				//
				sb.append("Content-Type: image/png"  + LINEND);
				sb.append(LINEND);
				//写入输出流中
				outStream.write(sb.toString().getBytes());
				//将文件读入输入流中
				InputStream is = new FileInputStream(file);
				byte[] buffer = new byte[1024];
				int len = -1;
				//写入输出流中
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}
				is.close();
				//添加换行标识
				outStream.write(LINEND.getBytes());
			}
			
			byte[] endData = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
			outStream.write(endData);
			//发送数据
			outStream.flush();
			//获取响应码 上传成功返回的是200
			int res = conn.getResponseCode();
			return res;
		}
	}

}

这样也能成功,





你可能感兴趣的:(两种android客户端传图片的方法)