- 第一种方法
- 写一个上传的类实现上传图片和文件的功能.
参考文件
android中的文件(图片)上传
这种方法需要开线程.
在onCreate方法中调用.
DownloadThread downloadThread = new DownloadThread();
downloadThread.start();
开线程.
class DownloadThread extends Thread{
@Override
public void run() {
try{
System.out.println("开始下载文件");
//文件下载完成后更新UI
String requestURL = "http://...";
String picPath = Environment.getExternalStorageDirectory()+"/xxx.jpg";
File file = new File(picPath);
Log.i("upload", "file exists:" + file.exists());
if (file.exists()) {
Map<String, String> params = new HashMap<>();
// 参数添加
params.put("xx", "xx");
String request = UploadUtil.uploadFile(file, requestURL, params, "xxx");
Log.i("upload", request);
}
//此处让线程DownloadThread休眠5秒中,模拟文件的耗时过程
Thread.sleep(5000);
System.out.println("文件下载完成");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
- 第二种方法
- 利用Okhttp3网络请求框架实现
参考文章
OKhttp3.X 3.0上传图片文件及表单MultipartBody
private void upFile(){
String requestURL = "http:..";
String picPath = Environment.getExternalStorageDirectory()+"/xx.jpg";
File file = new File(picPath);
Map<String, String> params = new