上次讲了如何拍照上传并保存图片至sd下,但只实现了拍照功能,却没有实现上传,这次补上咯...
其实对于上传自己也写过,也参考过别人的代码但是没有实现,无奈,只好去下载别人的源码了,这次终于实现了..
不多说,源码附上
1、当前类实现OnUploadProcessListener
它的方法是:这里用Handler去处理
1 //上传完成 2 @Override 3 public void onUploadDone(int responseCode, String message) { 4 Message msg = Message.obtain(); 5 msg.what = 3; 6 msg.arg1 = responseCode; 7 msg.obj = message; 8 handler.sendMessage(msg); 9 } 10 11 //正在上传 12 @Override 13 public void onUploadProcess(int uploadSize) { 14 Message msg=Message.obtain(); 15 msg.what=2; 16 msg.arg1=uploadSize; 17 handler.sendMessage(msg); 18 } 19 20 //开始上传 21 @Override 22 public void initUpload(int fileSize) { 23 Message msg=Message.obtain(); 24 msg.what=1; 25 msg.arg1=fileSize; 26 handler.sendMessage(msg); 27 }
2、实现上传调用方法(携带的参数正是图片所在sd路径)
1 //上传图片(当前图片的路径:imgpath、服务器的路径:requestURL,参数:param) 2 public void uploadMyPhoto(String imgpath){ 3 if(imgpath!=null){ 4 String filekey="img";//设置格式 5 UploadUtil uploadUtil = UploadUtil.getInstance();; 6 uploadUtil.setOnUploadProcessListener(this);//设置监听器监听上传状态 7 Map<String,String> param=new HashMap<String,String>(); 8 uploadUtil.uploadFile(imgpath, filekey, requestURL, param); 9 } 10 }
3、客户端上传的源码(UploadUtil工具类)
1 package com.techrare.utils; 2 3 import java.io.DataOutputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.net.HttpURLConnection; 9 import java.net.MalformedURLException; 10 import java.net.URL; 11 import java.util.Iterator; 12 import java.util.Map; 13 import java.util.UUID; 14 15 import android.util.Log; 16 17 //上传工具类 支持上传文件和参数 18 public class UploadUtil { 19 private static UploadUtil uploadUtil; 20 private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 21 private static final String PREFIX = "--"; 22 private static final String LINE_END = "\r\n"; 23 private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型 24 private UploadUtil() { 25 26 } 27 /** 28 * 单例模式获取上传工具类 29 * @return 30 */ 31 public static UploadUtil getInstance() { 32 if (null == uploadUtil) { 33 uploadUtil = new UploadUtil(); 34 } 35 return uploadUtil; 36 } 37 38 private static final String TAG = "UploadUtil"; 39 private int readTimeOut = 10 * 1000; // 读取超时 40 private int connectTimeout = 10 * 1000; // 超时时间 41 private static int requestTime = 0; //请求使用多长时间 42 private static final String CHARSET = "utf-8"; // 设置编码 43 public static final int UPLOAD_SUCCESS_CODE = 1; //上传成功 44 //文件不存在 45 public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2; 46 //服务器出错 47 public static final int UPLOAD_SERVER_ERROR_CODE = 3; 48 protected static final int WHAT_TO_UPLOAD = 1; 49 protected static final int WHAT_UPLOAD_DONE = 2; 50 51 /** 52 * android上传文件到服务器 53 * 54 * @param filePath 55 * 需要上传的文件的路径 56 * @param fileKey 57 * 在网页上<input type=file name=xxx/> xxx就是这里的fileKey 58 * @param RequestURL 59 * 请求的URL 60 */ 61 public void uploadFile(String filePath, String fileKey, String RequestURL, 62 Map<String, String> param) { 63 if (filePath == null) { 64 sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在"); 65 return; 66 } 67 try { 68 File file = new File(filePath); 69 uploadFile(file, fileKey, RequestURL, param); 70 } catch (Exception e) { 71 sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在"); 72 e.printStackTrace(); 73 return; 74 } 75 } 76 77 /** 78 * android上传文件到服务器 79 * 80 * @param file 81 * 需要上传的文件 82 * @param fileKey 83 * 在网页上<input type=file name=xxx/> xxx就是这里的fileKey 84 * @param RequestURL 85 * 请求的URL 86 */ 87 public void uploadFile(final File file, final String fileKey, 88 final String RequestURL, final Map<String, String> param) { 89 if (file == null || (!file.exists())) { 90 sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在"); 91 return; 92 } 93 94 Log.i(TAG, "请求的URL=" + RequestURL); 95 Log.i(TAG, "请求的fileName=" + file.getName()); 96 Log.i(TAG, "请求的fileKey=" + fileKey); 97 new Thread(new Runnable() { //开启线程上传文件 98 99 public void run() { 100 toUploadFile(file, fileKey, RequestURL, param); 101 } 102 }).start(); 103 104 } 105 106 private void toUploadFile(File file, String fileKey, String RequestURL, 107 Map<String, String> param) { 108 String result = null; 109 requestTime= 0; 110 111 long requestTime = System.currentTimeMillis(); 112 long responseTime = 0; 113 114 try { 115 URL url = new URL(RequestURL); 116 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 117 conn.setReadTimeout(readTimeOut); 118 conn.setConnectTimeout(connectTimeout); 119 conn.setDoInput(true); // 允许输入流 120 conn.setDoOutput(true); // 允许输出流 121 conn.setUseCaches(false); // 不允许使用缓存 122 conn.setRequestMethod("POST"); // 请求方式 123 conn.setRequestProperty("Charset", CHARSET); // 设置编码 124 conn.setRequestProperty("connection", "keep-alive"); 125 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); 126 conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); 127 // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 128 129 //当文件不为空,把文件包装并且上传 130 DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); 131 StringBuffer sb = null; 132 String params = ""; 133 134 /*** 135 * 以下是用于上传参数 136 */ 137 if (param != null && param.size() > 0) { 138 Iterator<String> it = param.keySet().iterator(); 139 while (it.hasNext()) { 140 sb = null; 141 sb = new StringBuffer(); 142 String key = it.next(); 143 String value = param.get(key); 144 sb.append(PREFIX).append(BOUNDARY).append(LINE_END); 145 sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END); 146 sb.append(value).append(LINE_END); 147 params = sb.toString(); 148 Log.i(TAG, key+"="+params+"##"); 149 dos.write(params.getBytes()); 150 // dos.flush(); 151 } 152 } 153 154 sb = null; 155 params = null; 156 sb = new StringBuffer(); 157 /** 158 * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 159 * filename是文件的名字,包含后缀名的 比如:abc.png 160 */ 161 sb.append(PREFIX).append(BOUNDARY).append(LINE_END); 162 sb.append("Content-Disposition:form-data; name=\"" + fileKey 163 + "\"; filename=\"" + file.getName() + "\"" + LINE_END); 164 sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的 165 sb.append(LINE_END); 166 params = sb.toString(); 167 sb = null; 168 169 Log.i(TAG, file.getName()+"=" + params+"##"); 170 dos.write(params.getBytes()); 171 /**上传文件*/ 172 InputStream is = new FileInputStream(file); 173 onUploadProcessListener.initUpload((int)file.length()); 174 byte[] bytes = new byte[1024]; 175 int len = 0; 176 int curLen = 0; 177 while ((len = is.read(bytes)) != -1) { 178 curLen += len; 179 dos.write(bytes, 0, len); 180 onUploadProcessListener.onUploadProcess(curLen); 181 } 182 is.close(); 183 184 dos.write(LINE_END.getBytes()); 185 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); 186 dos.write(end_data); 187 dos.flush(); 188 //dos.write(tempOutputStream.toByteArray()); 189 190 //获取响应码 200=成功 当响应成功,获取响应的流 191 int res = conn.getResponseCode(); 192 responseTime = System.currentTimeMillis(); 193 this.requestTime = (int) ((responseTime-requestTime)/1000); 194 Log.e(TAG, "response code:" + res); 195 if (res == 200) { 196 Log.e(TAG, "request success"); 197 InputStream input = conn.getInputStream(); 198 StringBuffer sb1 = new StringBuffer(); 199 int ss; 200 while ((ss = input.read()) != -1) { 201 sb1.append((char) ss); 202 } 203 result = sb1.toString(); 204 Log.e(TAG, "result : " + result); 205 sendMessage(UPLOAD_SUCCESS_CODE, "上传结果:" 206 + result); 207 return; 208 } else { 209 Log.e(TAG, "request error"); 210 sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:code=" + res); 211 return; 212 } 213 } catch (MalformedURLException e) { 214 sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage()); 215 e.printStackTrace(); 216 return; 217 } catch (IOException e) { 218 sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage()); 219 e.printStackTrace(); 220 return; 221 } 222 } 223 224 //发送上传结果 225 private void sendMessage(int responseCode,String responseMessage) 226 { 227 onUploadProcessListener.onUploadDone(responseCode, responseMessage); 228 } 229 230 //自定义的回调函数,用到回调上传文件是否完成 231 public static interface OnUploadProcessListener { 232 /** 233 * 上传响应 234 * @param responseCode 235 * @param message 236 */ 237 void onUploadDone(int responseCode, String message); 238 /** 239 * 上传中 240 * @param uploadSize 241 */ 242 void onUploadProcess(int uploadSize); 243 /** 244 * 准备上传 245 * @param fileSize 246 */ 247 void initUpload(int fileSize); 248 } 249 private OnUploadProcessListener onUploadProcessListener; 250 251 252 public void setOnUploadProcessListener(OnUploadProcessListener onUploadProcessListener) { 253 this.onUploadProcessListener = onUploadProcessListener; 254 } 255 256 public int getReadTimeOut() { 257 return readTimeOut; 258 } 259 260 public void setReadTimeOut(int readTimeOut) { 261 this.readTimeOut = readTimeOut; 262 } 263 264 public int getConnectTimeout() { 265 return connectTimeout; 266 } 267 268 public void setConnectTimeout(int connectTimeout) { 269 this.connectTimeout = connectTimeout; 270 } 271 //获取上传使用的时间 272 public static int getRequestTime() { 273 return requestTime; 274 } 275 276 public static interface uploadProcessListener{ 277 278 } 279 }
4、服务端的源码(服务端是用struts实现的)
1 package com.techrare.web; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.PrintWriter; 7 import java.text.DecimalFormat; 8 9 import org.apache.struts2.ServletActionContext; 10 import com.opensymphony.xwork2.ActionSupport; 11 12 public class UploadAction extends ActionSupport { 13 14 private String savePath; 15 /**这里的名字和html的名字必须对称*/ 16 private File img; 17 /**要上传的文件类型*/ 18 private String imgContentType; 19 /**文件的名称*/ 20 private String imgFileName; 21 /** 22 * 指定的上传类型 zip 和 图片格式的文件 23 */ 24 private static final String[] types = { "application/x-zip-compressed", 25 "ZIP", "image/pjpeg","image/x-png" }; //"application/octet-stream; charset=utf-8", 26 /*** 27 * 判断文件的类型是否为指定的文件类型 28 * @return 29 */ 30 public boolean filterType() { 31 boolean isFileType = false; 32 String fileType = getImgContentType(); 33 System.out.println(fileType); 34 for (String type : types) { 35 if (type.equals(fileType)) { 36 isFileType = true; 37 break; 38 } 39 } 40 return true; 41 } 42 43 public String getSavePath() { 44 String realPath = ServletActionContext.getRequest().getRealPath(savePath); 45 System.out.println("savePaht -- 保存地址" + realPath); 46 return realPath; 47 } 48 49 /** 50 * 取得文件夹大小 51 * @param f 52 * @return 53 * @throws Exception 54 */ 55 public long getFileSize(File f) throws Exception { 56 return f.length(); 57 } 58 59 public String FormetFileSize(long fileS) {// 转换文件大小 60 DecimalFormat df = new DecimalFormat("#.00"); 61 String fileSizeString = ""; 62 if (fileS < 1024) { 63 fileSizeString = df.format((double) fileS) + "B"; 64 } else if (fileS < 1048576) { 65 fileSizeString = df.format((double) fileS / 1024) + "K"; 66 } else if (fileS < 1073741824) { 67 fileSizeString = df.format((double) fileS / 1048576) + "M"; 68 } else { 69 fileSizeString = df.format((double) fileS / 1073741824) + "G"; 70 } 71 return fileSizeString; 72 } 73 74 /** 75 * 上传文件操作 76 * @return 77 * @throws Exception 78 */ 79 public String upload() throws Exception { 80 81 String ct = ServletActionContext.getRequest().getHeader("Content-Type"); 82 System.out.println("Content-Type=(访问头文件)"+ct); 83 String result = "unknow error"; 84 85 PrintWriter out = ServletActionContext.getResponse().getWriter(); 86 if (!filterType()) { 87 System.out.println("文件类型不正确"); 88 ServletActionContext.getRequest().setAttribute("typeError", 89 "您要上传的文件类型不正确"); 90 91 result = "error:" + getImgContentType() + " type not upload file type"; 92 } else { 93 System.out.println("当前文件大小为:" 94 + FormetFileSize(getFileSize(getImg()))); 95 FileOutputStream fos = null; 96 FileInputStream fis = null; 97 try { 98 // 保存文件那一个路径 99 fos = new FileOutputStream(getSavePath() + "\\" 100 + getImgFileName()); 101 fis = new FileInputStream(getImg()); 102 byte[] buffer = new byte[1024]; 103 int len = 0; 104 while ((len = fis.read(buffer)) > 0) { 105 fos.write(buffer, 0, len); 106 } 107 //result = "上传成功!"; 108 result = "Upload File Success !"; 109 } catch (Exception e) { 110 result = "Upload File Failed ! "; 111 e.printStackTrace(); 112 } finally { 113 fos.close(); 114 fis.close(); 115 } 116 } 117 out.print(result); 118 return null; 119 } 120 121 public File getImg() { 122 return img; 123 } 124 125 public String getImgFileName() { 126 return imgFileName; 127 } 128 129 public void setSavePath(String value) { 130 this.savePath = value; 131 } 132 133 public void setImgFileName(String imgFileName) { 134 this.imgFileName = imgFileName; 135 } 136 137 public void setImg(File img) { 138 this.img = img; 139 } 140 141 public String getImgContentType() { 142 return imgContentType; 143 } 144 145 public void setImgContentType(String imgContentType) { 146 this.imgContentType = imgContentType; 147 } 148 }
到这、拍照上传图片已经基本上实现了...