#服务端和客户端交互
服务器:接收文件,并且把文件,存储到指定目录,对文件进行命名的等操作。
客户端:选定文件,拼接参数,上传到指定服务器上。
#购买服务器(阿里云服务器或者自己搭建服务器)
#搭建服务器(软件服务器)
源码环境:
jre7 tomcat7
1、将.war文件复制到tomcat服务器webapps下,启动服务器即可
2、访问工程路径a即可测试上传
b/s架构 通过浏览器上传
c/s结构 通过Android端上传
上传文件服务地址:
http://192.168.10.168:8080/FileUpload/FileUploadServlet
#利用xUtils3上传多个文件,代码如下
// 上传多文件示例
@Event(value = R.id.btn_test2)
private void onTest2Click(View view) throws FileNotFoundException {
RequestParams params = new RequestParams("http://192.168.10.168:8080/FileUpload/FileUploadServlet");
// 加到url里的参数, http://xxxx/s?wd=xUtils
params.addQueryStringParameter("wd", "xUtils");//name=yangguangfu?password=1233445
// 添加到请求body体的参数, 只有POST, PUT, PATCH, DELETE请求支持.
// params.addBodyParameter("wd", "xUtils");
// 使用multipart表单上传文件
params.setMultipart(true);//设置支持多个文件上传
//具体的某一个文件
params.addBodyParameter(
"file1",
new File("/mnt/sdcard/1.jpg"),
null); // 如果文件没有扩展名, 最好设置contentType参数.
//具体的某一个文件
params.addBodyParameter(
"file2",
new File("/mnt/sdcard/2.jpg"),
null); // 如果文件没有扩展名, 最好设置contentType参数.
x.http().post(params, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
Toast.makeText(x.app(), result + "上传成功", Toast.LENGTH_LONG).show();
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
Toast.makeText(x.app(), ex.getMessage() + "上传失败", Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(CancelledException cex) {
Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
}
@Override
public void onFinished() {
Toast.makeText(x.app(), "onFinished", Toast.LENGTH_LONG).show();
}
});
}
#利用使用xUtils下载文件列表
下载地址:
http://192.168.10.168:8080/oppo.mp4
// 添加到下载列表
@Event(value = R.id.btn_test3)
private void onTest3Click(View view) throws DbException {
for (int i = 0; i < 5; i++) {
String url = et_url.getText().toString();//得到下载的地址
String label = i + "xUtils_" + System.nanoTime();//下载的到本地的命名
DownloadService.getDownloadManager().startDownload(
url, label,
"/sdcard/xUtils/" + label + ".mp4", true, false, null);
}
}
#利用使用xUtils下载单个文件
String url = "http://192.168.10.168:8080/oppo.mp4";
String label = "oppo_" + "afua" + System.nanoTime();
DownloadService.getDownloadManager().startDownload(
url, label,
"/sdcard/xUtils/" + label + ".mp4", true, false, null);
#打开下载列表
@Event(value = R.id.btn_test4)
private void onTest4Click(View view) throws DbException {
getActivity().startActivity(new Intent(getActivity(), DownloadActivity.class));
}
#AFinla的使用
1.添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.把jar包拷贝到项目的lib目录下
3.普通文本的请求,代码如下:
public void getDete(View view){
FinalHttp fh = new FinalHttp();
fh.get("https://github.com/yangfuhai/afinal", new AjaxCallBack(){
@Override
public void onLoading(long count, long current) { //每1秒钟自动被回调一次
textView.setText(current+"/"+count);
}
@Override
public void onSuccess(Object o) {
super.onSuccess(o);
textView.setText(o.toString());
}
@Override
public void onStart() {
//开始http请求的时候回调
}
});
}
4.Afinal文件的下载
public void downloadFile(View view){
FinalHttp fh = new FinalHttp();
fh.download("http://192.168.10.168:8080/oppo.mp4", "/mnt/sdcard/afinloop.mp4", new AjaxCallBack<File>() {
@Override
public void onSuccess(File file) {
super.onSuccess(file);
Toast.makeText(MainActivity.this,"下载成功",Toast.LENGTH_SHORT).show();
}
@Override
public AjaxCallBack<File> progress(boolean progress, int rate) {
return super.progress(progress, rate);
}
@Override
public void onStart() {
super.onStart();
Toast.makeText(MainActivity.this,"onStart",Toast.LENGTH_SHORT).show();
}
@Override
public void onLoading(long count, long current) {
super.onLoading(count, current);
}
@Override
public boolean isProgress() {
return super.isProgress();
}
@Override
public int getRate() {
return super.getRate();
}
});
//
}
下载地址:http://download.csdn.net/detail/sinat_32804317/9551489
#okhttp的使用 有三种使用方式
第一种使用方式.关联库文件
第二种使用方式.把jar拷贝到工程lib目录下关联jar
第三种使用方式.在联网情况下
compile ‘com.squareup.okhttp:okhttp:2.4.0‘
gradle: compile ‘com.squareup.okio:okio:1.5.0‘
#okhttp的使用 请求普通的文本
/**
* get请求
* 请求文本信息
* @param view
*/
public void getHtml(View view)
{
String url = "http://192.168.10.168:8080/zhbj/categories.json";
OkHttpUtils
.get()
.url(url)
.build()
.execute(new MyStringCallback());
}
public class MyStringCallback extends StringCallback
{
@Override
public void onBefore(Request request)
{
super.onBefore(request);
setTitle("loading...");
}
@Override
public void onAfter()
{
super.onAfter();
setTitle("Sample-okHttp");
}
@Override
public void onError(Request request, Exception e)
{
mTv.setText("onError:" + e.getMessage());
}
@Override
public void onResponse(String response)
{
mTv.setText("onResponse" + response);
}
@Override
public void inProgress(float progress)
{
Log.e(TAG, "inProgress:" + progress);
mProgressBar.setProgress((int) (100 * progress));
}
}
#okhttp的使用-大文件的下载
/**
* 下载文件
* @param view
*/
public void downloadFile(View view)
{
String url = "http://192.168.10.168:8080/oppo.mp4";
OkHttpUtils//
.get()//
.url(url)//
.build()//
.execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "okhttpoppo.mp4")//
{
@Override
public void onBefore(Request request)
{
super.onBefore(request);
}
@Override
public void inProgress(float progress)
{
mProgressBar.setProgress((int) (100 * progress));
}
@Override
public void onError(Request request, Exception e)
{
Log.e(TAG, "onError :" + e.getMessage());
}
@Override
public void onResponse(File file)
{
Log.e(TAG, "onResponse :" + file.getAbsolutePath());
}
});
}
#okhttp的使用-单个文件的上传
/**
* 上传文件
* @param view
*/
public void uploadFile(View view)
{
File file = new File(Environment.getExternalStorageDirectory(), "1.jpg");
if (!file.exists())
{
Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show();
return;
}
Map<String, String> params = new HashMap<>();
// params.put("username", "杨光福");
// params.put("password", "123");
Map<String, String> headers = new HashMap<>();
headers.put("APP-Key", "APP-Secret222");
headers.put("APP-Secret", "APP-Secret111");
String url = "http://192.168.10.168:8080/FileUpload/FileUploadServlet";
OkHttpUtils.post()//
.addFile("mFile", "agguigu-afu.jpe", file)//
.url(url)//
.params(params)//
.headers(headers)//
.build()//
.execute(new MyStringCallback());
}
#okhttp的使用-多个文件的上传
/**
* 多文件同时上传
* @param view
*/
public void multiFileUpload(View view)
{
File file = new File(Environment.getExternalStorageDirectory(), "1.jpg");
File file2 = new File(Environment.getExternalStorageDirectory(), "2.txt");
if (!file.exists()||!file2.exists())
{
Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show();
return;
}
Map<String, String> params = new HashMap<>();
// params.put("username", "杨光福");
// params.put("password", "123");
String url = "http://192.168.10.168:8080/FileUpload/FileUploadServlet";
OkHttpUtils.post()//
.addFile("mFile", "01.jpg", file)//
.addFile("mFile", "afua.txt", file2)//
.url(url)
.params(params)//
.build()//
.execute(new MyStringCallback());
}
#okhttp的使用-请求网络图片
/**
* 请求网络到图片
* @param view
*/
public void getImage(View view)
{
mTv.setText("");
String url = "http://images.csdn.net/20150817/1.jpg";
OkHttpUtils
.get()//
.url(url)//
.tag(this)//
.build()//
.connTimeOut(5000)
.readTimeOut(5000)
.writeTimeOut(5000)
.execute(new BitmapCallback() {
@Override
public void onError(Request request, Exception e) {
mTv.setText("onError:" + e.getMessage());
}
@Override
public void onResponse(Bitmap bitmap) {
//设置图片
mImageView.setImageBitmap(bitmap);
}
});
}
#Android-Universal-Image-Loader在ListView中使用
在使用Image-Loader之前需要在Application里面做初始化
public static void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
//设置当前线程的优先级
.threadPriority(Thread.NORM_PRIORITY - 2)
// 缓存显示不同大小的同一张图片
.denyCacheImageMultipleSizesInMemory()
//将保存的时候的URI名称用MD5 加密
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs() // Remove for release app
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
1.在适配器中配置信息
protected ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)////设置下载的图片是否缓存在内存中
.cacheOnDisc(true)////设置下载的图片是否缓存在SD卡中
.considerExifParams(true)//是否考虑JPEG图像EXIF参数(旋转,翻转)
.displayer(new RoundedBitmapDisplayer(20))//设置图片圆角
.build();
2.在适配器中的getView中请求图片如下代码:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
......
//第一个参数是:图片的地址,第二个参数是要绑定的图片,第三个参数处理图片的配置,第四个参数
imageLoader.displayImage(imageUrls[position], holder.image, options, animateFirstListener);
return view;
}
}
3.设置监听animateFirstListener代码如下
class ItemAdapter extends BaseAdapter {
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
..............
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);//显示图片的过程有一个渐变动画
displayedImages.add(imageUri);
}
}
}
}
#Android-Universal-Image-Loader在 GridView中使用
1.设置配置信息
protected ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
2.在适配器的getView中请求网络图片,请求图片的时候,带有加载进度,代码如下,
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.image);
holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
imageLoader.displayImage(imageUrls[position], holder.imageView, options, new SimpleImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
holder.progressBar.setProgress(0);
holder.progressBar.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
holder.progressBar.setVisibility(View.GONE);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
holder.progressBar.setVisibility(View.GONE);
}
}, new ImageLoadingProgressListener() {
@Override
public void onProgressUpdate(String imageUri, View view, int current,
int total) {
holder.progressBar.setProgress(Math.round(100.0f * current / total));
}
}
);
return view;
}
#Picasso 的加载图片库的使用
1.把jar拷贝到项目下lib里
下载jar包地址
http://square.github.io/picasso/#download
2.单独请求某一张图片的用法
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
3.在ListView中适配器的getView中用法
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.image_items, null);
viewHolder = new ViewHolder();
viewHolder.imageview = (ImageView) convertView.findViewById(R.id.imageview);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imageview.setImageResource(R.drawable.empty_photo);
//得到数据
String imageurl = imageThumbUrls[position];
//
Picasso.with(context).load(imageurl).into(viewHolder.imageview);
return convertView;
}
#Glide 的加载图片库的使用
1.需要在联网的情况下,在build.gradle文件中配置
compile ‘com.github.bumptech.glide:glide:3.7.0‘
compile ‘com.android.support:support-v4:22.2.1‘
2.请求单张图片代码如下:
Glide.with(context)
.load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
.into(ivImg);
3.在使用Lisview的适配器中,getView里使用,代码如下:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.image_items, null);
viewHolder = new ViewHolder();
viewHolder.imageview = (ImageView) convertView.findViewById(R.id.imageview);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imageview.setImageResource(R.drawable.empty_photo);
//得到数据
String imageurl = imageThumbUrls[position];
Glide
.with(context)
.load(imageurl)
.centerCrop()
.placeholder(R.drawable.empty_photo)
.crossFade()
.into(viewHolder.imageview);
return convertView;
}
#Android-gif-drawable的使用
1.联网框架和 添加Android-gif-drawable 的jar包
compile files(‘libs/android-async-http-1.4.5.jar‘)
compile files(‘libs/classes.jar‘)
2.加载单张gif动画图片
asyncHttpClient = new AsyncHttpClient();
asyncHttpClient
.get("http://cdn.duitang.com/uploads/item/201311/20/20131120213622_mJCUy.thumb.600_0.gif",
new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1,
byte[] arg2) {
// TODO Auto-generated method stub
GifDrawable drawable = null;
try {
drawable = new GifDrawable(arg2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
network_gifimageview
.setBackground(drawable);
dialog.dismiss();
}
@Override
public void onFailure(int arg0, Header[] arg1,
byte[] arg2, Throwable arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"加载网络图片出错", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
3.用Android-gif-drawabl在ListView 中加载gif动画
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final GifImageView imageView;
if (convertView == null) {
imageView = new GifImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(10, 10, 10, 10);
int size = AbsListView.LayoutParams.WRAP_CONTENT;
AbsListView.LayoutParams layoutParams = new GridView.LayoutParams(size, size);
imageView.setLayoutParams(layoutParams);
} else {
imageView = (GifImageView) convertView;
}
asyncHttpClient
.get(imageUrls.get(position),
new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
try {
GifDrawable drawable = new GifDrawable(bytes);
imageView
.setBackground(drawable);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
System.out.println(throwable.getMessage());
}
});
return imageView;
}
#PhotoView的使用-单张图片
作用,加载图片的时候,可以缩放图片
1.关联photoView的库
compile ‘com.nostra13.universalimageloader:universal-image-loader:1.9.3‘
compile project(‘:PhotoView_library‘)
2.在布局中定义PhotoView
<uk.co.senab.photoview.PhotoView
android:id="@+id/iv_photo"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
3.实例化控件并且设置相关的监听
ImageView mImageView = (ImageView) findViewById(R.id.iv_photo);
mCurrMatrixTv = (TextView) findViewById(R.id.tv_current_matrix);
Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
mImageView.setImageDrawable(bitmap);
// The MAGIC happens here!
mAttacher = new PhotoViewAttacher(mImageView);
// Lets attach some listeners, not required though!
mAttacher.setOnMatrixChangeListener(new MatrixChangeListener());
mAttacher.setOnPhotoTapListener(new PhotoTapListener());
private class MatrixChangeListener implements OnMatrixChangedListener {
@Override
public void onMatrixChanged(RectF rect) {
mCurrMatrixTv.setText(rect.toString());
}
}
private class PhotoTapListener implements OnPhotoTapListener {
@Override
public void onPhotoTap(View view, float x, float y) {
float xPercentage = x * 100f;
float yPercentage = y * 100f;
showToast(String.format(PHOTO_TAP_TOAST_STRING, xPercentage, yPercentage, view == null ? 0 : view.getId()));
}
}
#PhotoView的使用-ViewPager中使用
应用场景:类似于空间图片浏览效果
1.在布局文件中定义HackyViewPager类,它继承ViewPager的
<uk.co.senab.photoview.sample.HackyViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
2.设置适配器
mViewPager.setAdapter(new SamplePagerAdapter());
3.适配器具体代码如下:
static class SamplePagerAdapter extends PagerAdapter {
private static final int[] sDrawables = { R.drawable.wallpaper, R.drawable.wallpaper, R.drawable.wallpaper,
R.drawable.wallpaper, R.drawable.wallpaper, R.drawable.wallpaper };
@Override
public int getCount() {
return sDrawables.length;
}
@Override
public View instantiateItem(ViewGroup container, int position) {
PhotoView photoView = new PhotoView(container.getContext());
photoView.setImageResource(sDrawables[position]);
// Now just add PhotoView to ViewPager and return it
container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
return photoView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}