您的位置:首页 > 移动开发 > Android开发

【Android】多格式文件,上传/下载

2017-03-29 15:18 148 查看
今天给大家整理一款下载附件的代码,基于AsyncTask实现的,AsyncTask库需要配置,具体的网上太多了,以下是全部的代码调用方式什么的大家一定很清楚,剩下的就是自己试验一下吧,包名path需要改一下, js中也可以调用以下方法实现下载.查看,是全部的类文件不是代码段,复制新建类改下类名就可用

1 下载文件

package com.wew.gis.ShyBlockControls.Http;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ShyFileDown extends AsyncTask<Void, Integer, Integer> {

private ProgressDialog progressDialog;
private Context context;
private static File bitmapFile;
public static String path;

public ShyFileDown(Context context) {
this.context = context;
}

//点击(网络获取)
public void getNetworkUpdata(String path1) {
if(path1==null){
this.path = "http://192.168.0.28:8185/UploadFile/20170308/131334127975155372.jpg";
}else {
this.path = path1;
}
String[] pasths = path.split("/");
progressDialog = new ProgressDialog(context);
bitmapFile = new File(Environment.getExternalStorageDirectory(), "/temp/" + pasths[pasths.length-1]);

if (bitmapFile != null && bitmapFile.isFile() == true) {
ckbj(bitmapFile);
}else {
this.execute();
}
}

//execute被调用后立即执行
@Override
protected void onPreExecute() {
progressDialog.setTitle("正在下载...");
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);  //设置不可以取消(返回键)
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}

@Override
protected Integer doInBackground(Void... params) {
URL url;
HttpURLConnection connection = null;
InputStream in = null;
FileOutputStream out = null;
try {
url = new URL(path);
connection = (HttpURLConnection) url.openConnection();

in = connection.getInputStream();
long fileLength = connection.getContentLength();
File file_path = new File(Environment.getExternalStorageDirectory(), "/temp/");
if (!file_path.exists()) {
file_path.mkdir();
}

out = new FileOutputStream(new File(bitmapFile.getPath()));//为指定的文件路径创建文件输出流
byte[] buffer = new byte[1024 * 1024];
int len = 0;
long readLength = 0;

while ((len = in.read(buffer)) != -1) {

out.write(buffer, 0, len);//从buffer的第0位开始读取len长度的字节到输出流
readLength += len;
//下载进度
int curProgress = (int) (((float) readLength / fileLength) * 100);
publishProgress(curProgress);

if (readLength >= fileLength) {
break;
}
}

out.flush();
return 1;

} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if (connection != null) {
connection.disconnect();
}
}
return null;
}

//进度
@Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}

//结束
@Override
protected void onPostExecute(Integer integer) {
progressDialog.dismiss();//关闭进度条
ckbj(bitmapFile);
}

//查看浏览本机资源
private void ckbj(File file1) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
//获取文件file的MIME类型
String type = getMIMEType(file1);
//设置intent的data和Type属性。
intent.setDataAndType(Uri.fromFile(file1), type);
//跳转
context.startActivity(intent);
}

/**
* 根据文件后缀名获得对应的MIME类型。
*
* @param file
*/
private static String getMIMEType(File file) {

String type = "*/*";
String fName = file.getName();
//获取后缀名前的分隔符"."在fName中的位置。
int dotIndex = fName.lastIndexOf(".");
if (dotIndex < 0) {
return type;
}

/* 获取文件的后缀名*/
String end = fName.substring(dotIndex, fName.length()).toLowerCase();
if (end == "") return type;
//在MIME和文件类型的匹配表中找到对应的MIME类型。
for (int i = 0; i < MIME_MapTable.length; i++) { //MIME_MapTable??在这里你一定有疑问,这个MIME_MapTable是什么?
if (end.equals(MIME_MapTable[i][0]))
type = MIME_MapTable[i][1];
}
return type;
}

private static final String[][] MIME_MapTable = {
//{后缀名,MIME类型}
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".xls", "application/vnd.ms-excel"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prop", "text/plain"},
{".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"},
{".rtf", "application/rtf"},
{".sh", "text/plain"},
{".tar", "application/x-tar"},
{".tgz", "application/x-compressed"},
{".txt", "text/plain"},
{".wav", "audio/x-wav"},
{".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"},
{".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/x-zip-compressed"},
{"", "*/*"}
};
}

1 上传文件

package com.wew.gis.ShyBlockControls.Http;

import android.app.ProgressDialog;
import android.content.Context;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.wew.gis.util.Constants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;

import cz.msebera.android.httpclient.Header;

//附件上报
public class ShyFileUpdata {
public interface FileUpdataRequest {
public void Request(boolean b);
}
public interface OnUpDownRequest{
public void Request(String path);
}
af23
private static String sessionId = null;
private static AsyncHttpClient client = new AsyncHttpClient();
private static PersistentCookieStore cookieStore;

public static AsyncHttpClient getClient() {
return client;
}

/**
* 上传多个文件
*
* @param parameter 需要的jsonObject 参数
* @param paths     文件JsonArray 路径
*/
public static void uploadFile(final Context context, String parameter, String paths, final FileUpdataRequest fileRequest) {
if(paths.length()<=2){
return;
}
String url = Constants.UPLOAD_URL;
try {
JSONObject obj = new JSONObject(parameter);
final ProgressDialog dialog = new ProgressDialog(context);
dialog.setTitle("正在上传...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.show();
RequestParams params = new RequestParams();
JSONObject p = new JSONObject(parameter);
Iterator<String> keys = p.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = p.getString(key);
params.put(key, value);
}
JSONArray array = new JSONArray(paths);

for (int i = 0; i < array.length(); i++) {
String path = array.optString(i);
File file = new File(path);
if (file.exists() && file.length() > 0) {
params.put("File" + i, file);
} else {
Toast.makeText(context, path + "文件不存在", Toast.LENGTH_LONG).show();
}
}

AsyncHttpClient client = new AsyncHttpClient();

// 上传文件
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
dialog.dismiss();
if (fileRequest != null) {
fileRequest.Request(true);
}
Toast.makeText(context, "上传成功", Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
dialog.dismiss();
if (fileRequest != null) {
fileRequest.Request(false);
}
Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT).show();
}

@Override
public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
dialog.setProgress(count);
}
});

} catch (JSONException e) {
} catch (FileNotFoundException e) {
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 文件下载