http上传图片直接添加图片路径字段就可以上传了,而一般上传图片为了节省流量都会将图片压缩上传,网上有些很好的例子,
但是大多都是将图片压缩后保存在本地,再上传这个压缩后的图片,这样操作是可以,但是比较耗内存,多了两步操作(文件的读写),
而且在磁盘空间不足的情况下还会压缩失败,这里给出直接上传的方法;
先将图片解码获得图片的Bitmap,再将其压缩成指定大小,压缩后返回保存压缩后bitmap的流,这个流就是图片压缩后上传需要用的,
在http通信中有个InputStreamBody,根据压缩后的流创建这个body,然后添加到http实体中即可上传,具体看代码:
package com.yyu.utils; import java.io.File; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import com.yyu.listener.MyUploadListener; /** * @ClassName: MyUploadUtil * @Description: 文件上传工具类 依赖 httpmime-4.2.5.jar包 * @author yan.yu * @date 2014-2-13 下午2:04:52 */ public class MyUploadUtil { private boolean isStop = false; private MyUploadListener uploadListener = null; public void setOnUploadListener(MyUploadListener uploadListener) { this.uploadListener = uploadListener; } public void stop() { isStop = true; } /** * @Description: 上传图片 * @param @param fileList 图片列表 * @param @param url 服务器地址 * @param @param userId 用户ID * @param @param albumId 相册ID * @param @param compress 是否压缩上传 * @return void * @throws */ public void uploadFiles(List<File> fileList, String url, String userId, String albumId, boolean compress) { new UploadThread(fileList, url, userId, albumId, compress).start(); } /** * @throws JSONException * @throws IOException * @throws ClientProtocolException * @throws UnsupportedEncodingException * @Description: 上传文件,传入文件方式 * @param @param localFile 本地文件路径 * @param @param url 服务器地址 * @param @param userId 用户ID * @param @param albumId 相册ID * @param @return * @return String 文件在服务器地址 * @throws */ private String upload(String localFile, String url, String userId, String albumId, MyUploadListener listener) throws ClientProtocolException, IOException, JSONException { if(isStop) return null; String path = null; HttpClient httpclient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); File file = new File(localFile); MyMultipartEntity mpEntity = new MyMultipartEntity(listener, file.length()); //文件传输 if(userId != null) mpEntity.addPart("userId", new StringBody(userId)); if (albumId != null) mpEntity.addPart("albumId", new StringBody(albumId)); mpEntity.addPart("photoName", new StringBody(MyStringUtil.getLastByTag("/", localFile), Charset.forName("UTF-8"))); ContentBody cbFile = new FileBody(file); mpEntity.addPart("photoFile", cbFile); // <input type="file" name="userfile" /> 对应的 httpPost.setEntity(mpEntity); HttpResponse response = null; HttpEntity resEntity = null; response = httpclient.execute(httpPost, httpContext); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200) { String strResult = EntityUtils.toString(resEntity,"utf-8"); JSONObject jsonObject = new JSONObject(strResult); int result = 1; if(jsonObject.has("result")) { result = jsonObject.getInt("result"); if(result == 0) { if(jsonObject.has("pictureUrl")) path = jsonObject.getString("pictureUrl"); } } } if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); return path; } /** * @throws JSONException * @throws IOException * @throws ClientProtocolException * @throws UnsupportedEncodingException * @Description: 上传文件,传入文件流方式 * @param @param inputStream 文件流 * @param @param fileName 文件名字 * @param @param url 服务器地址 * @param @param userId 用户ID * @param @param albumId 相册ID * @param @return * @return String 文件在服务器上地址 * @throws */ private String upload(InputStream inputStream, String fileName, String url, String userId, String albumId, MyUploadListener listener) throws ClientProtocolException, IOException, JSONException { if(isStop) return null; String path = null; HttpClient httpclient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); long totalSize = inputStream.available(); MyMultipartEntity mpEntity = new MyMultipartEntity(listener, totalSize); //文件传输 mpEntity.addPart("userId", new StringBody(userId)); if (albumId != null) mpEntity.addPart("albumId", new StringBody(albumId)); mpEntity.addPart("photoName", new StringBody(fileName, Charset.forName("UTF-8"))); InputStreamBody isb = new InputStreamBody(inputStream, fileName); mpEntity.addPart("photoFile", isb); // <input type="file" name="userfile" /> 对应的 httpPost.setEntity(mpEntity); HttpResponse response = null; HttpEntity resEntity = null; response = httpclient.execute(httpPost, httpContext); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200) { String strResult = EntityUtils.toString(resEntity,"utf-8"); JSONObject jsonObject = new JSONObject(strResult); int result = 1; if(jsonObject.has("result")) { result = jsonObject.getInt("result"); if(result == 0) { if(jsonObject.has("pictureUrl")) path = jsonObject.getString("pictureUrl"); } } } if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); if(inputStream != null) inputStream.close(); return path; } class UploadThread extends Thread { private List<File> fileList = null; private String url = null; private String userId = null; private String albumId = null; private boolean compress = false; /** * <p>Title: </p> * <p>Description: </p> */ public UploadThread(List<File> fileList, String url, String userId, String albumId, boolean compress) { // TODO Auto-generated constructor stub this.fileList = fileList; this.url = url; this.userId = userId; this.albumId = albumId; this.compress = compress; } /** *callbacks */ @Override public void run() { // TODO Auto-generated method stub super.run(); int total = fileList.size(); int success = 0; if(uploadListener != null) uploadListener.onUploadSatrt(total);//上传开始 for(int i=0;i<total;i++) { if(isStop) { if(uploadListener != null) uploadListener.onUploadExit();//停止上传 break; } if(uploadListener != null) uploadListener.onUploadNumber(i, total);//开始上传第i个文件 File tempFile = fileList.get(i); String fileUrl = tempFile.getAbsolutePath(); String fileName = MyStringUtil.getLastByTag("/", fileUrl); if(tempFile.exists()) { InputStream inputStream = null; if(compress)//压缩 { long l = tempFile.length(); inputStream = MyBitmapUtil.compressImage(tempFile, Constant.COMPRESS_SIZE); } if(inputStream == null) { try { String path = upload(fileUrl, url, userId, albumId, uploadListener); if(!MyStringUtil.isEmpty(path)) { if(uploadListener != null) uploadListener.onUploadFinishOne(i);//第i个上传完成 success ++; } else { if(uploadListener != null) uploadListener.onUploadError();//第i个上传失败 } }catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); if(uploadListener != null) uploadListener.onUploadError(); } } else { try { String path = upload(inputStream, fileName, url, userId, albumId, uploadListener); if(!MyStringUtil.isEmpty(path)) { if(uploadListener != null) uploadListener.onUploadFinishOne(i);//第i个上传完成 success ++; } else { if(uploadListener != null) uploadListener.onUploadError();//第i个上传失败 } }catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); if(uploadListener != null) uploadListener.onUploadError(); } } } else//文件不存在 { if(uploadListener != null) uploadListener.onFileNotExist(fileName);//当前文件不存在 } } if(uploadListener != null) uploadListener.onUploadFinishAll(success, total - success);//全部上传完成 } } private final class MyMultipartEntity extends MultipartEntity { private MyUploadListener uploadlistener = null; private long totalSize = 0; public MyMultipartEntity(MyUploadListener uploadlistener, long totalSize) { this.uploadlistener = uploadlistener; this.totalSize = totalSize; } /** *callbacks */ @Override public void writeTo(OutputStream outstream) throws IOException { // TODO Auto-generated method stub super.writeTo(new MyOutputStream(outstream)); } private final class MyOutputStream extends FilterOutputStream { private int progress = 0; /** * <p>Title: </p> * <p>Description: </p> * @param out */ public MyOutputStream(OutputStream out) { super(out); // TODO Auto-generated constructor stub } public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); progress += len; if(uploadListener != null) uploadlistener.onUploadProgress(progress, (int) totalSize); } public void write(int b) throws IOException { out.write(b); } } } }
原文:http://blog.csdn.net/fireworkburn/article/details/19240507