随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
该示例直接使用流以POST方式进行文件上传,代码如下:
MainActivity:
package com.home.uploadfile;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button uploadBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
uploadBtn = (Button) findViewById(R.id.main_btn_upload);
uploadBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == uploadBtn) {
String requestUrl = "http://service.ireadhome.com/api/Upload/Image";
String filePath = "/storage/sdcard0/updateAdtech/orgpic/1.png";
File file = new File(filePath);
if (!file.exists()) {
Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_SHORT)
.show();
return;
}
LoadDialog dialog = new LoadDialog(MainActivity.this);
dialog.execute(new LoadDialog.Callback() {
@Override
public void getResult(Object obj) {
System.out.println(obj + "");
}
}, NetService.class, "postUseUrlConnection", requestUrl, file);
}
}
}
LoadDialog:
package com.home.uploadfile;
import java.lang.reflect.Method;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
/**
* 封装ProecssDialog对话框
*
* @author Administrator
*
*/
public class LoadDialog extends ProgressDialog {
private String title = "进度对话框";
private String message = "文件上传中。。。";
public LoadDialog(Context context, int theme) {
super(context, theme);
}
/**
* 用默认的标题和内容来创建对话框
*
* @param context
*/
public LoadDialog(Context context) {
super(context);
initDialog();
}
/**
* 用指定的标题和内容来创建对话框
*
* @param context
* @param title
* @param message
*/
public LoadDialog(Context context, String title, String message) {
super(context);
if (title != null) {
this.title = title;
}
if (message != null) {
this.message = message;
}
initDialog();
}
/**
* 初始化对话框参数,默认对话框不可以取消
*/
public void initDialog() {
setTitle(title);
setMessage(message);
setProgressStyle(ProgressDialog.STYLE_SPINNER);
setCancelable(false);
}
/**
* 打开对话框,设置回调方法,传递需要执行业务方法的类模板,方法名和参数列表
*
* @param callback
* 回调方法,该方法在对话框关闭后回调,并获取返回的数据
* @param serviceClass
* 执行业务方法的类模板
* @param method
* 执行业务方法的方法名
* @param params
* 执行业务方法的参数列表
*/
public void execute(Callback callback, Class serviceClass, String method,
Object... params) {
super.show();
ServiceAysnTask task = new ServiceAysnTask(callback, serviceClass,
method);
task.execute(params);
}
/**
* 回调方法的接口
*
* @author Administrator
*
*/
public interface Callback {
public void getResult(Object obj);
}
/**
* 与远程服务通信的线程类
*
* @author Administrator
*
*/
private class ServiceAysnTask extends AsyncTask<Object, Object, Object> {
private Class serviceClass;
private String method;
private Callback callback;
public ServiceAysnTask(Callback callback, Class serviceClass,
String method) {
this.callback = callback;
this.serviceClass = serviceClass;
this.method = method;
}
@Override
protected Object doInBackground(Object... params) {
Object resultObj = null;
try {
Object obj = serviceClass.newInstance();
Class[] paramTypes = new Class[params.length];
for (int i = 0; i < paramTypes.length; i++) {
paramTypes[i] = params[i].getClass();
}
Method m = serviceClass.getMethod(method, paramTypes);
resultObj = m.invoke(obj, params);
} catch (Exception e) {
e.printStackTrace();
}
LoadDialog.this.cancel();
return resultObj;
}
@Override
protected void onPostExecute(Object resultObj) {
super.onPostExecute(resultObj);
callback.getResult(resultObj);
}
}
}
NetService:
package com.home.uploadfile;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetService {
/**
* 以POST方式上传文件
*
* @param requestUrl
* @param file
* @return
*/
public static String postUseUrlConnection(String requestUrl, File file) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String newName = "image.jpg";
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 允许Input、Output,不使用Cache
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
// 设置以POST方式进行传送
con.setRequestMethod("POST");
// 设置RequestProperty
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
// 构造DataOutputStream流
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"file1\";filename=\"" + newName + "\"" + end);
ds.writeBytes(end);
// 构造要上传文件的FileInputStream流
FileInputStream fis = new FileInputStream(file);
// 设置每次写入1024bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
// 从文件读取数据至缓冲区
while ((length = fis.read(buffer)) != -1) {
// 将资料写入DataOutputStream中
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
// 关闭流
fis.close();
ds.flush();
// 获取响应流
InputStream is = con.getInputStream();
int ch;
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
// 关闭DataOutputStream
ds.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
}
权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />