主要思路是调用系统文件管理器或者其他媒体采集资源来获取要上传的文件,然后将文件的上传进度实时展示到进度条中。
主Activity
复制代码 代码如下:
package com.guotop.elearn.activity.app.yunpan.activity;
import java.io.file;
import java.io.fileNotFoundException;
import java.io.IOException;
import androID.app.Activity;
import androID.content.Intent;
import androID.content.res.Configuration;
import androID.net.Uri;
import androID.os.Bundle;
import androID.os.Environment;
import androID.provIDer.MediaStore;
import androID.provIDer.MediaStore.Audio.Media;
import androID.vIEw.LayoutInflater;
import androID.vIEw.VIEw;
import androID.vIEw.VIEw.OnClickListener;
import androID.Widget.button;
import androID.Widget.linearLayout;
import com.guotop.base.activity.BaseActivity;
import com.guotop.base.util.Myfile;
import com.guotop.elearn.activity.R;
import com.guotop.elearn.activity.app.yunpan.item.YunPanUploadfileItem;
/**
*
*
* @author: 李杨
* @time: 2014-4-15下午4:29:35
*/
public class YunPanUploadfileActivity extends BaseActivity implements OnClickListener{
String userID,parentID;
private final static int fileCHOOSER_RESulTCODE = 0;
// private String openfileType="";
private String mVIDeofilePath,mPhotofilePath,mVoicefilePath;
private button chooseBtn,uploadBtn;
private linearLayout conterLayout;
private String actionURL;
@OverrIDe
public voID onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState,this);
setTitle("云盘上传文件");
setContentVIEw(R.layout.activity_yunpan_uploadfile);
userID = getIntent().getStringExtra("userID");
parentID = getIntent().getStringExtra("parentID");
actionURL = getIntent().getStringExtra("actionURL");
chooseBtn = (button)findVIEwByID(R.ID.chooseBtn);
uploadBtn = (button)findVIEwByID(R.ID.uploadBtn);
conterLayout = (linearLayout)findVIEwByID(R.ID.conterLayout);
chooseBtn.setonClickListener(this);
uploadBtn.setonClickListener(this);
}
@OverrIDe
public voID onClick(VIEw v) {
if(v.getID()==R.ID.chooseBtn){
// //选择文件
startActivityForResult(createDefaultopenableIntent(),YunPanUploadfileActivity.fileCHOOSER_RESulTCODE);
// Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
// startActivityForResult(intent,YunPanUploadfileActivity.fileCHOOSER_RESulTCODE);
// Intent intent = new Intent(Media.RECORD_SOUND_ACTION);
// ((Activity) context).startActivityForResult(intent,YunPanUploadfileActivity.fileCHOOSER_RESulTCODE);
}else if(v.getID()==R.ID.uploadBtn){
//上传文件
}
}
/**
* 创建上传文件
*/
public voID createUploadfileItem(String filePath){
// VIEw vIEw = LayoutInflater.from(context).inflate(R.layout.activity_yunpan_uploadfile_item,null);
new YunPanUploadfileItem(context,conterLayout,filePath,actionURL);
}
@OverrIDe
public voID onConfigurationChanged(Configuration newConfig) {
// Todo auto-generated method stub
super.onConfigurationChanged(newConfig);
}
/**选择文件*/
private Intent createDefaultopenableIntent() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addcategory(Intent.category_OPENABLE);
i.putExtra(Intent.EXTRA_Title,"选择文件");
i.setType("*/*");
Intent chooser = createChooserIntent(createCameraIntent(),createCamcorderIntent(),createSoundRecorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT,i);
return chooser;
}
private Intent createChooserIntent(Intent... intents) {
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS,intents);
chooser.putExtra(Intent.EXTRA_Title,"选择文件");
return chooser;
}
private Intent createCameraIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
file cameraDataDir = new file(externalDataDir.getabsolutePath() + file.separator + "e-photos");
cameraDataDir.mkdirs();
mPhotofilePath = cameraDataDir.getabsolutePath() + file.separator + System.currentTimeMillis() + ".jpg";
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromfile(new file(mPhotofilePath)));
return cameraIntent;
}
private Intent createCamcorderIntent() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
file externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
file cameraDataDir = new file(externalDataDir.getabsolutePath() + file.separator + "e-vIDeos");
cameraDataDir.mkdirs();
mVIDeofilePath = cameraDataDir.getabsolutePath() + file.separator + System.currentTimeMillis() + ".3gp";
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromfile(new file(mVIDeofilePath)));
intent.putExtra(MediaStore.EXTRA_VIDEO_QUAliTY,1); // set the vIDeo
return intent;
}
private Intent createSoundRecorderIntent() {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
file externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
file cameraDataDir = new file(externalDataDir.getabsolutePath() + file.separator + "e-voices");
cameraDataDir.mkdirs();
mVoicefilePath = cameraDataDir.getabsolutePath() + file.separator + System.currentTimeMillis() + ".amr";
return intent;
}
protected voID onActivityResult(int requestCode,int resultCode,Intent data) {
if (requestCode == fileCHOOSER_RESulTCODE) {
Uri result= data == null || resultCode != RESulT_OK ? null :data.getData();
if (result == null && data == null && resultCode == Activity.RESulT_OK) {
file mMediafile = null;;
if(new file(mVIDeofilePath).exists()){
mMediafile = new file(mVIDeofilePath);
}else if(new file(mPhotofilePath).exists()){
mMediafile = new file(mPhotofilePath);
}else if(new file(mVoicefilePath).exists()){
mMediafile = new file(mVoicefilePath);
}
if (mMediafile!=null&&mMediafile.exists()) {
result = Uri.fromfile(mMediafile);
sendbroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_file,result));
}
// result = Uri.fromfile(new file(mCamerafilePath));
}
if(result!=null){
if(!new file(result.getPath()).canRead()){
try {
Myfile.copyfile(new file(mVoicefilePath),getContentResolver().openinputStream(result));
createUploadfileItem(mVoicefilePath);
} catch (fileNotFoundException e) {
e.printstacktrace();
}
}else {
createUploadfileItem(result.getPath());
}
}
System.out.println(result);
}
}
}
绘制现在文件信息后的Item
复制代码 代码如下:
package com.guotop.elearn.activity.app.yunpan.item;
import java.io.file;
import java.lang.ref.WeakReference;
import java.util.Random;
import org.Json.JsONException;
import org.Json.JsONObject;
import androID.app.AlertDialog;
import androID.content.Context;
import androID.content.DialogInterface;
import androID.content.Intent;
import androID.os.IBinder;
import androID.os.Looper;
import androID.os.Message;
import androID.vIEw.LayoutInflater;
import androID.vIEw.VIEw;
import androID.vIEw.VIEw.OnClickListener;
import androID.Widget.button;
import androID.Widget.ImageVIEw;
import androID.Widget.linearLayout;
import androID.Widget.Progressbar;
import androID.Widget.TextVIEw;
import androID.Widget.Toast;
import com.guotop.base.L;
import com.guotop.base.handler.BaseHandler;
import com.guotop.base.thread.httpThread;
import com.guotop.base.util.Myfile;
import com.guotop.base.util.MyHashMap;
import com.guotop.elearn.activity.R;
import com.guotop.elearn.activity.app.yunpan.Y;
import com.guotop.elearn.activity.app.yunpan.bean.UploadYunfileInformaction;
import com.guotop.elearn.activity.app.yunpan.thread.UploadYunfilehttpThread;
/**
*
*
* @author: 李杨
* @time: 2014-4-21下午12:28:33
*/
public class YunPanUploadfileItem implements OnClickListener {
linearLayout vIEw,parentVIEw;
String filePath;
private Context context;
private TextVIEw uploadfileProgresstext,uploadfilename;
private Progressbar uploadfileProgressbar;
private ImageVIEw uploadfileimg;
private button startUploadfileBtn,cancelUploadfileBtn;
private String actionURL;
BaseHandler handler;
UploadYunfilehttpThread t;
UploadYunfileInformaction uploadYunfileInformaction ;
public YunPanUploadfileItem(Context context,linearLayout parentVIEw,String filePath,String actionURL) {
this.parentVIEw = parentVIEw;
this.actionURL = actionURL;
this.context = context;
file file = new file(filePath);
this.vIEw = (linearLayout) LayoutInflater.from(context).inflate(R.layout.activity_yunpan_uploadfile_item,null);
// this.vIEw = vIEw;
this.filePath = filePath;
uploadfileProgresstext = (TextVIEw) vIEw.findVIEwByID(R.ID.uploadfileProgresstext);
uploadfilename = (TextVIEw) vIEw.findVIEwByID(R.ID.uploadfilename);
uploadfileProgressbar = (Progressbar) vIEw.findVIEwByID(R.ID.uploadfileProgressbar);
uploadfileimg = (ImageVIEw) vIEw.findVIEwByID(R.ID.uploadfileimg);
cancelUploadfileBtn = (button) vIEw.findVIEwByID(R.ID.cancelUploadfileBtn);
startUploadfileBtn = (button) vIEw.findVIEwByID(R.ID.startUploadfileBtn);
uploadfilename.setText(file.getname()+" 大小"+Myfile.formetfileSize(file.getPath()));
uploadfileimg.setimageResource(Myfile.getfileIcon(file));
startUploadfileBtn.setonClickListener(this);
cancelUploadfileBtn.setonClickListener(this);
parentVIEw.addVIEw(vIEw);
uploadYunfileInformaction = new UploadYunfileInformaction(filePath);
myHandler = new MyHandler(Looper.myLooper(),this);
uploadYunfileInformaction.setNotificationID(new Random().nextInt(10000));
uploadYunfileInformaction.setActionURL(actionURL);
t = new UploadYunfilehttpThread(myHandler,uploadYunfileInformaction);
uploads.put(uploadYunfileInformaction.getNotificationID(),t);
}
@OverrIDe
public voID onClick(VIEw v) {
if (v.getID() == R.ID.startUploadfileBtn) {
downfile(t);
startUploadfileBtn.setClickable(false);
}else if(v.getID()==R.ID.cancelUploadfileBtn){
if(t.isstart){
new AlertDialog.Builder(context).setTitle("系统提示!").setMessage("该文件正在上传确定要强制停止?")
.setNegativebutton("取消",new DialogInterface.OnClickListener() {
public voID onClick(DialogInterface dialog,int which) {
}
}).setPositivebutton("确定",int which) {
t.interrupt();
parentVIEw.removeVIEw(vIEw);
uploads.removeKey(uploadYunfileInformaction.getNotificationID());
System.gc();
}
}).show();
}else {
parentVIEw.removeVIEw(vIEw);
uploads.removeKey(uploadYunfileInformaction.getNotificationID());
}
}
}
public static MyHashMap<Integer,UploadYunfilehttpThread> uploads = new MyHashMap<Integer,UploadYunfilehttpThread>();
private MyHandler myHandler;
public IBinder onBind(Intent intent) {
return null;
}
// 下载更新文件
private voID downfile(UploadYunfilehttpThread t) {
int len = 3;
if (t != null && uploads.size() <= len) {
if (!t.isstart) {
t.start();
}
} else if (t == null && uploads.size() >= len) {
t = uploads.get(len - 1);
if (!t.isstart) {
t.start();
}
}
}
/* 事件处理类 */
class MyHandler extends BaseHandler {
private WeakReference<YunPanUploadfileItem> bdfs;
public MyHandler(Looper looper,YunPanUploadfileItem yunPanUploadfileItem) {
super(looper);
this.bdfs = new WeakReference<YunPanUploadfileItem>(yunPanUploadfileItem);
}
@OverrIDe
public voID handleMessage(Message msg) {
YunPanUploadfileItem bdfs = this.bdfs.get();
if (bdfs == null) {
return;
}
if (msg != null) {
switch (msg.what) {
case 0:
Toast.makeText(L.livingActivity,msg.obj.toString(),Toast.LENGTH_SHORT).show();
break;
case L.dowloadStart:
break;
case L.dowloadFinish:
// 下载完成后清除所有下载信息,执行安装提示
try {
uploads.removeKey(msg.getData().getInt("notificationID"));
bdfs.uploadfileProgresstext.setText("上传完成");
bdfs.uploadfileProgressbar.setMax(100);
bdfs.uploadfileProgressbar.setProgress(100);
startUploadfileBtn.setClickable(false);
} catch (Exception e) {
}
bdfs.downfile(null);
break;
case L.dowloadPercentage:
// 更新状态栏上的下载进度信息
bdfs.uploadfileProgresstext.setText("总共:"+Myfile.formetfileSize(msg.getData().getInt("fileSize"))+ "/" + Myfile.formetfileSize(msg.getData().getInt("finishfileSize")) + " 已上传"
+ msg.getData().getInt("percentage") + "%");
bdfs.uploadfileProgressbar.setMax(100);
bdfs.uploadfileProgressbar.setProgress(msg.getData().getInt("percentage"));
break;
case 4:
// bdfs.nm.cancel(msg.getData().getInt("notificationID"));
break;
}
}
}
}
}
用来上传文件的线程
复制代码 代码如下:
package com.guotop.elearn.activity.app.yunpan.thread;
import java.net.socketException;
import com.guotop.base.L;
import com.guotop.base.Util;
import com.guotop.base.handler.BaseHandler;
import com.guotop.base.thread.httpThread;
import com.guotop.elearn.activity.app.yunpan.bean.UploadYunfileInformaction;
import com.guotop.elearn.activity.app.yunpan.util.YunPanUploadfile;
import com.guotop.elearn.activity.app.yunpan.util.YunPanUploadfilehttpInterface;
/**
*
* 下载云服务器上的文件
*
*
*@author: 李杨
*@time: 2014-4-11下午6:06:53
*/
public class UploadYunfilehttpThread extends httpThread{
@SuppressWarnings("unused")
private UploadYunfileInformaction uploadYunfileInformaction;
public boolean isstart=false;
public static int RECONNECT = 1000002;
public static int CAN_NOT_RECONNECT = 1000003;
YunPanUploadfile yunPanUploadfile;
public UploadYunfilehttpThread(){
}
public UploadYunfilehttpThread(BaseHandler handler,UploadYunfileInformaction dowfile){
this.uploadYunfileInformaction=dowfile;
this.handler=handler;
}
int fileSize,finishfileSize,percentage;
private boolean isUpdate = true;
public voID run() {
isstart=true;//是启动了
new httpThread(handler){
public voID run() {
while (isUpdate) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
if(finishfileSize!=0&&fileSize!=0){
msg = handler.obtainMessage();
if(percentage>=100){
// msg.what=L.dowloadFinish;
// msg.setData(bundle);
// handler.sendMessage(msg);
break;
}else {
bundle.putString("filename",uploadYunfileInformaction.getfilename());
bundle.putInt("percentage",percentage);
bundle.putInt("finishfileSize",finishfileSize);
bundle.putInt("fileSize",fileSize);
msg.what=L.dowloadPercentage;
msg.setData(bundle);
handler.sendMessage(msg);
sendMessage(1000000);// 为了取消等待框
}
}
}
}
}.start();
try {
uploadfile();
} catch (Exception e) {
isUpdate = false;
isstart = false;
}
}
private voID uploadfile() {
yunPanUploadfile = new YunPanUploadfile(dbfInterface,uploadYunfileInformaction,L.cookie);
result = yunPanUploadfile.post();
msg = handler.obtainMessage();
bundle.putInt("notificationID",uploadYunfileInformaction.getNotificationID());
bundle.putString("path",uploadYunfileInformaction.getPath());
bundle.putString("result",result);
msg.what = L.dowloadFinish;
msg.setData(bundle);
handler.sendMessage(msg);
isUpdate = false;
isstart = false;
}
YunPanUploadfilehttpInterface dbfInterface = new YunPanUploadfilehttpInterface() {
//初始化下载后
public voID initfileSize(int size) {
fileSize=size;
msg = handler.obtainMessage();
bundle.putInt("fileSize",fileSize);
msg.what = L.dowloadStart;
msg.setData(bundle);
handler.sendMessage(msg);
}
//现在计划进行中
public voID uploadplan(int fileSize,int finishSize) {
finishfileSize=finishSize;
percentage=finishSize/(fileSize/100);
if(percentage<-1L){
Util.LogGL(this.getClass().getname(),"downloadplan",percentage+"");
}
}
//下载完成
public voID uploadFinish(String file) {
percentage=101;
}
};
public UploadYunfileInformaction getDowloadfileInformaction() {
return uploadYunfileInformaction;
}
public voID setDowloadfileInformaction(
UploadYunfileInformaction dowloadfileInformaction) {
this.uploadYunfileInformaction = dowloadfileInformaction;
}
@OverrIDe
public voID interrupt() {
yunPanUploadfile.close();
super.interrupt();
}
}
记录文件信息Bean
复制代码 代码如下:
package com.guotop.elearn.activity.app.yunpan.item;
import java.io.file;
import java.lang.ref.WeakReference;
import java.util.Random;
import org.Json.JsONException;
import org.Json.JsONObject;
import androID.app.AlertDialog;
import androID.content.Context;
import androID.content.DialogInterface;
import androID.content.Intent;
import androID.os.IBinder;
import androID.os.Looper;
import androID.os.Message;
import androID.vIEw.LayoutInflater;
import androID.vIEw.VIEw;
import androID.vIEw.VIEw.OnClickListener;
import androID.Widget.button;
import androID.Widget.ImageVIEw;
import androID.Widget.linearLayout;
import androID.Widget.Progressbar;
import androID.Widget.TextVIEw;
import androID.Widget.Toast;
import com.guotop.base.L;
import com.guotop.base.handler.BaseHandler;
import com.guotop.base.thread.httpThread;
import com.guotop.base.util.Myfile;
import com.guotop.base.util.MyHashMap;
import com.guotop.elearn.activity.R;
import com.guotop.elearn.activity.app.yunpan.Y;
import com.guotop.elearn.activity.app.yunpan.bean.UploadYunfileInformaction;
import com.guotop.elearn.activity.app.yunpan.thread.UploadYunfilehttpThread;
/**
*
*
* @author: 李杨
* @time: 2014-4-21下午12:28:33
*/
public class YunPanUploadfileItem implements OnClickListener {
linearLayout vIEw,Toast.LENGTH_SHORT).show();
break;
case L.dowloadStart:
break;
case L.dowloadFinish:
// 下载完成后清除所有下载信息,执行安装提示
try {
uploads.removeKey(msg.getData().getInt("notificationID"));
bdfs.uploadfileProgresstext.setText("上传完成");
bdfs.uploadfileProgressbar.setMax(100);
bdfs.uploadfileProgressbar.setProgress(100);
startUploadfileBtn.setClickable(false);
} catch (Exception e) {
}
bdfs.downfile(null);
break;
case L.dowloadPercentage:
// 更新状态栏上的下载进度信息
bdfs.uploadfileProgresstext.setText("总共:"+Myfile.formetfileSize(msg.getData().getInt("fileSize"))+ "/" + Myfile.formetfileSize(msg.getData().getInt("finishfileSize")) + " 已上传"
+ msg.getData().getInt("percentage") + "%");
bdfs.uploadfileProgressbar.setMax(100);
bdfs.uploadfileProgressbar.setProgress(msg.getData().getInt("percentage"));
break;
case 4:
// bdfs.nm.cancel(msg.getData().getInt("notificationID"));
break;
}
}
}
}
}
文件上传工具类
复制代码 代码如下:
package com.guotop.elearn.activity.app.yunpan.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.file;
import java.io.fileinputStream;
import java.io.fileNotFoundException;
import java.io.IOException;
import java.io.inputStreamReader;
import java.io.UnsupportedEnCodingException;
import java.net.httpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import androID.R.integer;
import com.guotop.elearn.activity.app.yunpan.bean.UploadYunfileInformaction;
/**
*
*
*
* @author: 李杨
* @time: 2013-6-13下午7:07:36
*/
public class YunPanUploadfile {
String multipart_form_data = "multipart/form-data";
String twoHyphens = "--";
String boundary = "****************SoMeTeXtWeWiLlNeVeRsEe"; // 数据分隔符
String lineEnd = "\r\n";
YunPanUploadfilehttpInterface yunPanUploadfilehttpInterface;
UploadYunfileInformaction uploadYunfileInformaction;
String cookie;
public YunPanUploadfile(YunPanUploadfilehttpInterface yunPanUploadfilehttpInterface,UploadYunfileInformaction uploadYunfileInformaction,String cookie){
this.yunPanUploadfilehttpInterface = yunPanUploadfilehttpInterface;
this.uploadYunfileInformaction = uploadYunfileInformaction;
this.cookie = cookie;
}
public voID write(UploadYunfileInformaction file,DataOutputStream output) {
fileinputStream in;
try {
if (file.getPath() != null && !"".equals(file.getPath())) {
in = new fileinputStream(new file(file.getPath()));
int fileSize= in.available();
int readySize = 0;
yunPanUploadfilehttpInterface.initfileSize(fileSize);
byte[] b = new byte[1024];
while (in.read(b) > 0) {
readySize+=b.length;
yunPanUploadfilehttpInterface.uploadplan(fileSize,readySize);
output.write(b,b.length);
}
}
output.writeBytes(lineEnd);
} catch (fileNotFoundException e) {
e.printstacktrace();
} catch (UnsupportedEnCodingException e) {
e.printstacktrace();
} catch (IOException e) {
e.printstacktrace();
}
}
/*
* 构建表单字段内容,格式请参考http 协议格式(用FireBUG可以抓取到相关数据)。(以便上传表单相对应的参数值) 格式如下所示:
* --****************fD4fH3hK7aI6 Content-disposition: form-data;
* name="action" // 一空行,必须有 upload
*/
private voID addFormFIEld(Map<String,String> params,DataOutputStream output) {
if (params != null) {
for (Entry<String,String> param : params.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append(twoHyphens + boundary + lineEnd);
sb.append("Content-disposition: form-data; name=\"" + param.getKey() + "\"" + lineEnd);
sb.append(lineEnd);
sb.append(param.getValue() + lineEnd);
try {
output.write(sb.toString().getBytes("utf-8"));// 发送表单字段数据
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
/**
* 直接通过 http 协议提交数据到服务器,实现表单提交功能。
*
* @param actionUrl
* 上传路径
* @param params
* 请求参数key为参数名,value为参数值
* @param uploadYunfileInformaction
* 上传文件信息
* @return 返回请求结果
*/
public String post(){
return post(null,cookie);
}
public String post(UploadYunfileInformaction uploadYunfileInformaction,String cookie,YunPanUploadfilehttpInterface yunPanUploadfilehttpInterface) {
return post(null,cookie);
}
httpURLConnection conn = null;
DataOutputStream output = null;
BufferedReader input = null;
public String post(Map<String,String cookie) {
try {
URL url = new URL(uploadYunfileInformaction.getActionURL());
conn = (httpURLConnection) url.openConnection();
conn.setRequestProperty("cookie",cookie);
conn.setConnectTimeout(120000);
conn.setDoinput(true); // 允许输入
conn.setDoOutput(true); // 允许输出
conn.setUseCaches(false); // 不使用Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset","utf-8");
conn.setRequestProperty("Accept-EnCoding","gzip,deflate");
conn.setRequestProperty("Connection","keep-alive");
conn.setRequestProperty("Content-Type",multipart_form_data + "; boundary=" + boundary);
conn.setChunkedStreamingMode(1024*1024);//设置上传文件的缓存大小
conn.connect();
output = new DataOutputStream(conn.getoutputStream());
//发送头数据
sendSplithead(uploadYunfileInformaction,output);
//发送文件内容
write(uploadYunfileInformaction,output);
//发送表单数据
addFormFIEld(params,output); // 添加表单字段内容
output.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);// 数据结束标志
output.flush();
int code = conn.getResponseCode();
if (code != 200) {
throw new RuntimeException("请求‘" + uploadYunfileInformaction.getActionURL() + "'失败!");
}
input = new BufferedReader(new inputStreamReader(conn.getinputStream()));
StringBuilder response = new StringBuilder();
String oneline;
while ((oneline = input.readline()) != null) {
response.append(oneline + lineEnd);
}
yunPanUploadfilehttpInterface.uploadFinish(uploadYunfileInformaction.getPath());
return response.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
close();
}
}
public voID close(){
// 统一释放资源
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
if (conn != null) {
conn.disconnect();
}
}
//发送头数据
public voID sendSplithead(UploadYunfileInformaction uploadYunfileInformaction,DataOutputStream output){
StringBuilder split = new StringBuilder();
split.append(twoHyphens + boundary + lineEnd);
try {
split.append("Content-disposition: form-data; name=\"" + uploadYunfileInformaction.getFormname() + "\"; filename=\""
+ new String(uploadYunfileInformaction.getfilename().getBytes(),"iso8859-1") + "\"" + lineEnd);
} catch (UnsupportedEnCodingException e1) {
// Todo auto-generated catch block
e1.printstacktrace();
}
split.append("Content-Type: " + uploadYunfileInformaction.getContentType() + lineEnd);
split.append(lineEnd);
// 发送数据
try {
output.writeBytes(split.toString());
} catch (IOException e) {
// Todo auto-generated catch block
e.printstacktrace();
}
}
}
Layout 文件内容
activity_yunpan_uploadfile_item.xml
复制代码 代码如下:
<?xml version="1.0" enCoding="utf-8"?>
<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"
androID:layout_wIDth="fill_parent"
androID:layout_height="match_parent"
androID:padding="5dp"
androID:orIEntation="horizontal" >
<relativeLayout
androID:ID="@+ID/TitleLayout"
androID:layout_wIDth="match_parent"
androID:layout_height="match_parent"
androID:gravity="top" >
<linearLayout
androID:ID="@+ID/TitleCenter"
androID:layout_wIDth="wrap_content"
androID:layout_height="wrap_content"
androID:layout_centerVertical="true"
androID:layout_toleftOf="@+ID/TitleRigth"
androID:layout_toRightOf="@+ID/titelleft"
androID:gravity="left"
androID:orIEntation="vertical" >
<TextVIEw
androID:ID="@+ID/uploadfileProgresstext"
androID:layout_wIDth="fill_parent"
androID:layout_height="wrap_content"
androID:text="上传进度"
androID:textAppearance="?androID:attr/textAppearanceLarge" />
<Progressbar
androID:ID="@+ID/uploadfileProgressbar"
androID:layout_wIDth="match_parent"
androID:layout_height="wrap_content" />
<TextVIEw
androID:ID="@+ID/uploadfilename"
androID:layout_wIDth="fill_parent"
androID:layout_height="wrap_content"
androID:text="文件名称"
androID:textAppearance="?androID:attr/textAppearanceLarge" />
</linearLayout>
<linearLayout
androID:ID="@+ID/titelleft"
androID:layout_wIDth="100dp"
androID:layout_height="100dp"
androID:layout_alignBaseline="@+ID/TitleCenter"
androID:layout_alignBottom="@+ID/TitleCenter"
androID:layout_alignParentleft="true"
androID:orIEntation="vertical" >
</linearLayout>
<linearLayout
androID:ID="@+ID/TitleRigth"
androID:layout_wIDth="wrap_content"
androID:layout_height="wrap_content"
androID:layout_alignParentRight="true"
androID:layout_centerVertical="true"
androID:layout_marginRight="21dp"
androID:orIEntation="horizontal" >
<button
androID:ID="@+ID/startUploadfileBtn"
androID:layout_wIDth="wrap_content"
androID:layout_height="wrap_content"
androID:text="开始" />
<button
androID:ID="@+ID/cancelUploadfileBtn"
androID:layout_wIDth="wrap_content"
androID:layout_height="wrap_content"
androID:text="取消" />
</linearLayout>
<ImageVIEw
androID:ID="@+ID/uploadfileimg"
androID:layout_wIDth="100dp"
androID:layout_height="100dp"
androID:layout_centerVertical="true"
androID:layout_toleftOf="@+ID/TitleCenter" />
</relativeLayout>
</linearLayout>
activity_yunpan_uploadfile.xml
复制代码 代码如下:
<?xml version="1.0" enCoding="utf-8"?>
<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"
androID:layout_wIDth="fill_parent"
androID:layout_height="match_parent"
androID:orIEntation="vertical" >
<relativeLayout
androID:ID="@+ID/TitleLayout"
androID:layout_wIDth="fill_parent"
androID:layout_height="wrap_content"
androID:gravity="top" >
<!-- <linearLayout -->
<!-- androID:ID="@+ID/TitleRigth" -->
<!-- androID:layout_wIDth="wrap_content" -->
<!-- androID:layout_height="wrap_content" -->
<!-- androID:layout_alignBaseline="@+ID/TitleCenter" -->
<!-- androID:layout_alignBottom="@+ID/TitleCenter" -->
<!-- androID:layout_alignParentRight="true" -->
<!-- androID:orIEntation="vertical" > -->
<!-- <button -->
<!-- androID:layout_wIDth="wrap_content" -->
<!-- androID:layout_height="wrap_content" -->
<!-- androID:text="TitleRigth" /> -->
<!-- </linearLayout> -->
<!-- <linearLayout -->
<!-- androID:ID="@+ID/TitleCenter" -->
<!-- androID:layout_wIDth="wrap_content" -->
<!-- androID:layout_height="wrap_content" -->
<!-- androID:layout_alignParenttop="true" -->
<!-- androID:layout_toleftOf="@+ID/TitleRigth" -->
<!-- androID:layout_toRightOf="@+ID/titelleft" -->
<!-- androID:gravity="left" -->
<!-- androID:orIEntation="vertical" > -->
<!-- <button -->
<!-- androID:layout_wIDth="fill_parent" -->
<!-- androID:layout_height="wrap_content" -->
<!-- androID:text="TitleCenter" /> -->
<!-- </linearLayout> -->
<linearLayout
androID:ID="@+ID/titelleft"
androID:layout_wIDth="match_parent"
androID:layout_height="wrap_content"
androID:layout_alignBaseline="@+ID/TitleCenter"
androID:layout_alignBottom="@+ID/TitleCenter"
androID:layout_alignParentleft="true"
androID:orIEntation="horizontal" >
<button
androID:ID="@+ID/chooseBtn"
androID:layout_weight="1"
androID:layout_wIDth="match_parent"
androID:layout_height="wrap_content"
androID:text="选择文件" />
<button
androID:ID="@+ID/uploadBtn"
androID:layout_weight="1"
androID:layout_wIDth="match_parent"
androID:layout_height="wrap_content"
androID:text="全部开始上传" />
</linearLayout>
</relativeLayout>
<relativeLayout
androID:layout_wIDth="fill_parent"
androID:layout_height="fill_parent" >
<ScrollVIEw
androID:ID="@+ID/scrollVIEw1"
androID:layout_above="@+ID/bottom"
androID:layout_wIDth="match_parent"
androID:layout_height="match_parent" >
<linearLayout
androID:ID="@+ID/conterLayout"
androID:layout_wIDth="match_parent"
androID:layout_height="wrap_content"
androID:gravity="top"
androID:orIEntation="vertical" >
</linearLayout>
</ScrollVIEw>
<linearLayout
androID:ID="@+ID/bottom"
androID:layout_wIDth="fill_parent"
androID:layout_height="wrap_content"
androID:layout_alignParentBottom="true"
androID:gravity="bottom"
androID:orIEntation="vertical" >
</linearLayout>
</relativeLayout>
</linearLayout>
以上是内存溢出为你收集整理的android文件上传示例分享(android图片上传)全部内容,希望文章能够帮你解决android文件上传示例分享(android图片上传)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)