Android开发中有很多情况下,需要实现向服务器上传图片,比如说开发APP过程需要实现上传头像等信息。这篇文章给出了Android终端上传头像图片的方法与简析。
上传工具类:
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; /** * * 上传工具类 * */ public class UploadUtils { private static final String TAG = "upload"; private static final int TIME_OUT = 1000 * 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=\"upload\"; 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(); // if(res==200) // { InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); System.out.println(result); // if(res==200) // { // } // else{ // Log.e(TAG, "request error"); // } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
图片上传封装类:
import java.io.File; import android.os.Environment; public class TUploadFile { private static TUploadFile mTUploadFile = null; private TUploadFile() { } public synchronized static TUploadFile getInstance() { if (mTUploadFile == null) mTUploadFile = new TUploadFile(); return mTUploadFile; } public String TUploadHeadImage(String cusId) {//用户ID号,上传头像,一个用户对应一个头像 String result = ""; //比如说通过拍照裁剪后先保存在本地命名为myphoto.png,然后从本地上传到服务器上 result = UploadUtils.uploadFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/myphoto.png"),"服务器域名" + cusId); return result; } }
APP应用中保存全局变量的Application类:
public class TestApplication extends Application { private static TestApplication mInstance = null; public static TUploadFile mTUploadFile; // 单例模式中获取唯一的TestApplication实例 public static TestApplication getInstance() { if (null == mInstance) mInstance = new TestApplication(); return mInstance; } public void onCreate() { super.onCreate(); mTUploadFile = TUploadFile.getInstance(); } }
采用异步方式进行上传头像图片的方法:
public class AsyncHeadUpTask extends AsyncTask<String, Integer, String> { // 上传头像 protected String doInBackground(String... params) { String code = ""; try { String result = TestApplication.mTUploadFile.TUploadHeadImage(params[0]);//参数为用户ID JSONObject resultCode = new JSONObject(result); code = resultCode.getString("commonACK");//服务器端返回的验证码 } catch (Exception e) { e.printStackTrace(); } return code; } protected void onPostExecute(String result) { stopProgressDialog();//上传成功后停止延迟动画 if (result.equals("111111")) {// 服务器返回来的验证码为111111时表示上传头像成功 Toast.makeText(getActivity(), "上传头像成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "网络连接错误", Toast.LENGTH_SHORT).show(); } } protected void onPreExecute() { super.onPreExecute(); startUpProgressDialog();//上传延时动画 } }
原文地址:http://blog.csdn.net/wtyvhreal/article/details/41826919