上篇 学习了 图片 的 选择 和 加载 ,遗留两个小问题;
(1)Android-Ultra-Photo-Selector 开源框架下载
http://download.csdn.net/detail/lablenet/9074975
(2)demo 有偿下载
http://download.csdn.net/detail/lablenet/9074969
(1)图片上传 (多图上传/单张也可以使用)
(2)服务端实现
(3)图片加载 (Volley 二次开发实现)
(4)ViewFlipper (图片轮播)实现加载 网络图片
(1) 图片上传有多种实现方式:常用的是 HttpClient ,UrlConnection , AsyncHttpClient 三种方式实现;
(2) HttpClient和 AsyncHttpClient 类似,后面将学习 使用 AsyncHttpClient实现图片上传;
(3)相比UrlConnection来说 ,各有各得优点;
(4)使用HttpClient 在 进行 图片压缩的时候,使用了 以 临时文件的形式进行了保存,而不能直接 上传 文件流;
(5)注意:实际上在 HttpMime4.5.jar 可以直接上传 文件流的,需要倒入 HttpCore.jar 包, 但是我尝试了,又引发了,版本号问题,索性就使用了 文件 保存 压缩后的文件;(eclipse)
(6)UrlConnection 在 模拟 表单提交的时候,需要细心点就可以了;
(7) HttpClient 直接上传文件流的实现需要的jar包:
http://download.csdn.net/detail/lablenet/9075023
(8)HttClient 以临时文件的形式上传文件的方式需要的jar包(我自己的实现方式):
http://download.csdn.net/detail/lablenet/9074767
(1)通过 MultipartEntity 实现 参数 提交
(2)PictureUtil.bitmapToPath() 方法 实现了 图片压缩 :
参数为:原图地址;
返回值:压缩后临时图片的地址;
图片压缩知识,见上篇;
(3)上传的是 压缩后的图片;
// 上传
public String httpClientUpload() throws ClientProtocolException,
IOException {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(UploadPath.uploadImagePath());
HttpContext localContext = new BasicHttpContext();
// 模拟浏览器提交
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// 可以添加其他信息
// multipartEntity.addPart()
// 添加图片信息
// 添加多张图片信息
for (int i = 0; i < imgPaths.size(); i++) {
// FileBody fileBody = new FileBody(getFile(imgPaths.get(i)));
String tmepName = PictureUtil.bitmapToPath(imgPaths.get(i));
File file = new File(tmepName);
FileBody fileBody = new FileBody(file);
//存储临时文件名
imgstmppath.add(tmepName);
// ByteArrayBody byteArrayBody=new ByteArrayBody(buffer,tmepName);
Log.i("tag","........................................"+tmepName);
multipartEntity.addPart("file" + i, fileBody);
}
// 设置 上传
httpPost.setEntity(multipartEntity);
HttpResponse response = client.execute(httpPost, localContext);
String str = getJsonString("请求失败");
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回数据
str = EntityUtils.toString(response.getEntity());
}
return str;
}
(1)安卓4.0 及其之后版本 不允许 在 UI线程 进行网络请求,
(2)实现 线程+Handler实现 ,上传图片,拿到 返回过来的json数据
(3)PictureUtil.bitmapToPath() 方法 实现了 图片压缩 :
参数为:原图地址;
返回值:压缩后临时图片的地址;
图片压缩知识,见上篇;
(4)消息发送给 Handler后 ,使用PicturcUtil.deleteImgTmp()删除临时文件;
(5)imgstmpPath 集合 存放的是 返回的临时文件路径(目的删除它)
package com.example.upload;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
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 android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.example.Util.PictureUtil;
@SuppressWarnings("deprecation")
public class UploadImage extends Thread {
private Handler handler;
private List imgPaths;
private List imgstmppath=new ArrayList();
// 构造
public UploadImage(Handler handler, List imgPaths) {
// 上传
this.handler = handler;
this.imgPaths = imgPaths;
}
// 上传
public String httpClientUpload() throws ClientProtocolException,
IOException {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(UploadPath.uploadImagePath());
HttpContext localContext = new BasicHttpContext();
// 模拟浏览器提交
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// 可以添加其他信息
// multipartEntity.addPart()
// 添加图片信息
// 添加多张图片信息
for (int i = 0; i < imgPaths.size(); i++) {
// FileBody fileBody = new FileBody(getFile(imgPaths.get(i)));
String tmepName = PictureUtil.bitmapToPath(imgPaths.get(i));
File file = new File(tmepName);
FileBody fileBody = new FileBody(file);
//存储临时文件名
imgstmppath.add(tmepName);
// ByteArrayBody byteArrayBody=new ByteArrayBody(buffer,tmepName);
Log.i("tag","........................................"+tmepName);
multipartEntity.addPart("file" + i, fileBody);
}
// 设置 上传
httpPost.setEntity(multipartEntity);
HttpResponse response = client.execute(httpPost, localContext);
String str = getJsonString("请求失败");
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回数据
str = EntityUtils.toString(response.getEntity());
}
return str;
}
// 得到文件
// public File getFile(String imgpath) {
//
// File file=new File(imgpath);
// return file;
// }
@Override
public void run() {
// 执行上传操作
String msg = getJsonString("请求失败");
try {
msg = httpClientUpload();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
msg = getJsonString(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
msg = getJsonString(e.getMessage());
}
Message message = handler.obtainMessage();
message.obj = msg;
handler.sendMessage(message);
//执行删除临时文件操作
PictureUtil.deleteImgTmp(imgstmppath);
}
private String getJsonString(String msg) {
return "{\"msg\":\"" + msg + "\"}";
}
}
(1)Servlet 3.0 及其以上 版本
(2)Tomcat 7.0 及其以上 版本
(1)注意图片存放路径(Tomact 下)
(2)@MultipartConfig() 标签实现
@MultipartConfig(location ="E:\\andriod\\demo\\workspace5\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\UploadEmo\\Image", maxFileSize = 10L*1024L * 1024L,// 每一个文件的最大值
maxRequestSize = 1024L * 1024L * 100L
// 一次上传最大值,若每次只能上传一个文件,则设置maxRequestSize意义不大
// 若不指定的话,就没有限制了,也可以 上传
// 服务器图片绝对路径:为 location 的位置)
http://download.csdn.net/detail/lablenet/9002259
package cn.labelnet.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import net.sf.json.JSONObject;
/**
* Servlet implementation class UploadImage
*/
@WebServlet("/UploadImage")
@MultipartConfig(location ="E:\\andriod\\demo\\workspace5\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\UploadEmo\\Image", maxFileSize = 10L*1024L * 1024L,// 每一个文件的最大值
maxRequestSize = 1024L * 1024L * 100L
// 一次上传最大值,若每次只能上传一个文件,则设置maxRequestSize意义不大
// 若不指定的话,就没有限制了,也可以 上传
// 服务器图片绝对路径:"E:\\andriod\\demo\\workspace5\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\UploadEmo\\Image"
)
public class UploadImage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UploadImage() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 实现图片上传
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String str = "服务器错误,上传失败!";
List parts = (List) request.getParts();
// 保存文件名
Map names = new HashMap();
try {
for (int i=0;i 0) {
str = "上传成功";
}
String jsondata = getJSONdata(str, names);
System.out.println(jsondata);
response.setContentType("text/json");
PrintWriter out = response.getWriter();
out.write(jsondata);
out.flush();
out.close();
}
/*
* Java文件操作 获取文件扩展名
*/
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot, filename.length() - 1);
}
}
return filename;
}
private String getName() {
String[] strs = { "yuan", "ming", "zhuo" };
Random random = new Random();
int x = random.nextInt(10000000);
int y = random.nextInt(3);
String name = x + strs[y];
return name;
}
// 封装数据
private String getJSONdata(String msg,Map names) {
Map maps = new HashMap();
maps.put("msg", msg);
if (names.size() > 0) {
maps.put("data", names);
} else {
maps.put("data", "[\"img1\":\"moren.jpg\"]");
}
JSONObject jsonObject = JSONObject.fromObject(maps);
return jsonObject.toString();
}
}
(1)加载图片实现
http://blog.csdn.net/lablenet/article/details/47859613
(2)ViewFlipper 图片轮播实现
Android-ViewFlipper(图片轮播 和 手势控制 实例)
http://blog.csdn.net/lablenet/article/details/47974187
实现 Volley 加载网络图片 到 ViewFlipper实现 图片轮播;
private void getPictures(ArrayList urls) {
if (urls.size() > 0) {
// 加载图片
for (String url : urls) {
ImageView imageView = new ImageView(this);
ImageListener listener = ImageLoader.getImageListener(
imageView, R.drawable.moren, R.drawable.fail);
VolleyHttpRequest.Image_Loader(url, listener);
vf_one.addView(imageView);
}
} else {
// 出错的情况下
int[] ids = { R.drawable.tubiao, R.drawable.fail,
R.drawable.tubiao, R.drawable.fail };
for (int i : ids) {
ImageView view = new ImageView(this);
view.setImageResource(i);
vf_one.addView(view);
}
}
//vf_one.setInAnimation(this, Animation.ZORDER_BOTTOM);
vf_one.setFlipInterval(3000);
//vf_one.setOutAnimation(this, Animation.ZORDER_TOP);
vf_one.startFlipping();
}
http://download.csdn.net/detail/lablenet/9074969