登录 / 注册
WebView基于H5的上传和和下载
发布时间:2019-01-27 12:41:03 查看:3372
现在混合开发APP已经 成为了一种趋势,某些功能用H5解决的就用H5来做了,最近遇到一个需求,就是在H5界面里面有一个图片上传功能,还有附件下载功能,安卓的 webView如果不通过一些设置的话是不可以的。下面要说的就是用H5来打开手机的图库,并进行图片上传功能,还有下载功能。
首先是要继承WebChromeClient这个类,WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等。
  1. class MyWebChromeClient extends WebChromeClient {
  2. // For Android 3.0+
  3. public void openFileChooser(ValueCallback<Uri> uploadMsg,
  4. String acceptType) {
  5. if (mUploadMessage != null)
  6. return;
  7. mUploadMessage = uploadMsg;
  8. selectImage(RESULT_CODE_PICK_FROM_ALBUM_BELLOW_LOLLILOP);
  9. }
  10. // For Android < 3.0
  11. public void openFileChooser(ValueCallback<Uri> uploadMsg) {
  12. openFileChooser(uploadMsg, "");
  13. }
  14. // For Android > 4.1.1
  15. public void openFileChooser(ValueCallback<Uri> uploadMsg,
  16. String acceptType, String capture) {
  17. openFileChooser(uploadMsg, acceptType);
  18. }
  19. // For Android 5.0+
  20. public boolean onShowFileChooser(WebView webView,
  21. ValueCallback<Uri[]> filePathCallback,
  22. FileChooserParams fileChooserParams) {
  23. mUploadCallbackAboveL = filePathCallback;
  24. selectImage(RESULT_CODE_PICK_FROM_ALBUM_ABOVE_LOLLILOP);
  25. return true;
  26. }
  27. @Override
  28. public void onProgressChanged(WebView view, int newProgress) {
  29. super.onProgressChanged(view, newProgress);
  30. }
  31. }
openFileChooser和onShowFileChooser方法,当网络上页面点击了<input type="file"/>的标签时,不同版本的SDK调用openFileChooser或者onShowFileChooser。
选 择完图片后,进入onActivityResult,根据不同的requestCode值区分开AndroidSDK 5.0以上和5.0以下,5.0以下传回Uri对象,5.0以上传回Uri数组。其中处理下onActivityResult传回来的意图数据,将 Intent数据转换乌里分类中翻译。
	
  1. /**选择后,回传值*/
  2. @Override
  3. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  4. super.onActivityResult(requestCode, resultCode, data);
  5. if (mUploadMessage == null && mUploadCallbackAboveL == null) {
  6. return;
  7. }
  8. Uri uri = null;
  9. switch (requestCode) {
  10. case RESULT_CODE_PICK_FROM_ALBUM_BELLOW_LOLLILOP:
  11. uri = afterChosePic(data);
  12. if (mUploadMessage != null) {
  13. mUploadMessage.onReceiveValue(uri);
  14. mUploadMessage = null;
  15. }
  16. break;
  17. case RESULT_CODE_PICK_FROM_ALBUM_ABOVE_LOLLILOP:
  18. try {
  19. uri = afterChosePic(data);
  20. if (uri == null) {
  21. mUploadCallbackAboveL.onReceiveValue(new Uri[] { });
  22. mUploadCallbackAboveL = null;
  23. break;
  24. }
  25. if (mUploadCallbackAboveL != null && uri != null) {
  26. mUploadCallbackAboveL.onReceiveValue(new Uri[] { uri });
  27. mUploadCallbackAboveL = null;
  28. }
  29. } catch (Exception e) {
  30. mUploadCallbackAboveL = null;
  31. e.printStackTrace();
  32. }
  33. break;
  34. }
  35. }
	
  1. **
  2. 下面把完整的代码贴上来:
  3. **
  4. WebViewActivity.java
  5. package com.lwd.webviewupimg;
  6. import java.io.File;
  7. import android.annotation.SuppressLint;
  8. import android.app.Activity;
  9. import android.content.ContentResolver;
  10. import android.content.Intent;
  11. import android.database.Cursor;
  12. import android.graphics.Bitmap;
  13. import android.net.Uri;
  14. import android.os.Bundle;
  15. import android.os.Environment;
  16. import android.provider.MediaStore.Images.ImageColumns;
  17. import android.view.KeyEvent;
  18. import android.view.View;
  19. import android.webkit.ValueCallback;
  20. import android.webkit.WebChromeClient;
  21. import android.webkit.WebSettings;
  22. import android.webkit.WebSettings.LayoutAlgorithm;
  23. import android.webkit.WebView;
  24. import android.webkit.WebViewClient;
  25. /**
  26. * @author lwd
  27. * @create 2016年8月17日
  28. */
  29. @SuppressLint("SetJavaScriptEnabled")
  30. public class WebViewActivity extends Activity{
  31. private WebView webview;
  32. private ValueCallback<Uri> mUploadMessage;
  33. private ValueCallback<Uri[]> mUploadCallbackAboveL;
  34. private final int RESULT_CODE_PICK_FROM_ALBUM_BELLOW_LOLLILOP = 1;
  35. private final int RESULT_CODE_PICK_FROM_ALBUM_ABOVE_LOLLILOP = 2;
  36. private String url = "";//这里添加含有图片上传功能的H5页面访问地址即可。
  37. String compressPath = "";
  38. @Override
  39. protected void onCreate(Bundle savedInstanceState) {
  40. super.onCreate(savedInstanceState);
  41. setContentView(R.layout.activity_welcome);
  42. initData();
  43. }
  44. public void initData() {
  45. webview = (WebView) findViewById(R.id.webview);
  46. initWebView();
  47. webview.loadUrl(url);
  48. }
  49. @SuppressWarnings("deprecation")
  50. private void initWebView(){
  51. webview.setScrollBarStyle(View.GONE);
  52. webview.getSettings().setJavaScriptEnabled(true);
  53. webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
  54. webview.getSettings().setDomStorageEnabled(false);
  55. webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
  56. webview.getSettings().setPluginState(WebSettings.PluginState.ON);
  57. webview.getSettings().setAllowFileAccess(true);
  58. webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
  59. webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
  60. webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
  61. webview.getSettings().setUseWideViewPort(true);
  62. webview.getSettings().setLoadWithOverviewMode(true);
  63. webview.getSettings().setAllowContentAccess(true);
  64. webview.requestFocus();
  65. webview.setWebViewClient(new WebClient());
  66. webview.setWebChromeClient(new MyWebChromeClient());
  67. }
  68. /**选择后,回传值*/
  69. @Override
  70. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  71. super.onActivityResult(requestCode, resultCode, data);
  72. if (mUploadMessage == null && mUploadCallbackAboveL == null) {
  73. return;
  74. }
  75. Uri uri = null;
  76. switch (requestCode) {
  77. case RESULT_CODE_PICK_FROM_ALBUM_BELLOW_LOLLILOP:
  78. uri = afterChosePic(data);
  79. if (mUploadMessage != null) {
  80. mUploadMessage.onReceiveValue(uri);
  81. mUploadMessage = null;
  82. }
  83. break;
  84. case RESULT_CODE_PICK_FROM_ALBUM_ABOVE_LOLLILOP:
  85. try {
  86. uri = afterChosePic(data);
  87. if (uri == null) {
  88. mUploadCallbackAboveL.onReceiveValue(new Uri[] { });
  89. mUploadCallbackAboveL = null;
  90. break;
  91. }
  92. if (mUploadCallbackAboveL != null && uri != null) {
  93. mUploadCallbackAboveL.onReceiveValue(new Uri[] { uri });
  94. mUploadCallbackAboveL = null;
  95. }
  96. } catch (Exception e) {
  97. mUploadCallbackAboveL = null;
  98. e.printStackTrace();
  99. }
  100. break;
  101. }
  102. }
  103. /**
  104. * 选择照片后结束
  105. * @param data
  106. */
  107. private Uri afterChosePic(Intent data) {
  108. if (data == null) {
  109. return null;
  110. }
  111. String path = getRealFilePath(data.getData());
  112. String[] names = path.split("\\.");
  113. String endName = null;
  114. if (names != null) {
  115. endName = names[names.length - 1];
  116. }
  117. if (endName != null) {
  118. compressPath = compressPath.split("\\.")[0] + "." + endName;
  119. }
  120. File newFile;
  121. try {
  122. newFile = FileUtils.compressFile(path, compressPath);
  123. } catch (Exception e) {
  124. newFile = null;
  125. }
  126. return Uri.fromFile(newFile);
  127. }
  128. /**
  129. * 根据Uri获取图片文件的绝对路径
  130. */
  131. public String getRealFilePath(final Uri uri) {
  132. if (null == uri) {
  133. return null;
  134. }
  135. final String scheme = uri.getScheme();
  136. String data = null;
  137. if (scheme == null) {
  138. data = uri.getPath();
  139. } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
  140. data = uri.getPath();
  141. } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
  142. Cursor cursor = getContentResolver().query(uri,
  143. new String[] { ImageColumns.DATA }, null, null, null);
  144. if (null != cursor) {
  145. if (cursor.moveToFirst()) {
  146. int index = cursor.getColumnIndexOrThrow(ImageColumns.DATA);
  147. if (index > -1) {
  148. data = cursor.getString(index);
  149. }
  150. }
  151. cursor.close();
  152. }
  153. }
  154. return data;
  155. }
  156. @Override
  157. public void onBackPressed() {
  158. super.onBackPressed();
  159. if(webview.canGoBack()){
  160. webview.goBack();
  161. }else{
  162. finish();
  163. }
  164. }
  165. private class WebClient extends WebViewClient {
  166. @Override
  167. public void onPageStarted(WebView view, String url, Bitmap favicon) {
  168. super.onPageStarted(view, url, favicon);
  169. }
  170. @Override
  171. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  172. view.loadUrl(url);
  173. return true;
  174. }
  175. @Override
  176. public void onPageFinished(WebView view, String url) {
  177. super.onPageFinished(view, url);
  178. }
  179. }
  180. @Override
  181. public boolean onKeyDown(int keyCode, KeyEvent event) {
  182. if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
  183. webview.goBack();
  184. return true;
  185. }
  186. return super.onKeyDown(keyCode, event);
  187. }
  188. /**打开图库,同时处理图片(项目业务需要统一命名)*/
  189. private void selectImage(int resultCode) {
  190. compressPath = Environment.getExternalStorageDirectory().getPath() + "/QWB/temp";
  191. File file = new File(compressPath);
  192. if (!file.exists()) {
  193. file.mkdirs();
  194. }
  195. compressPath = compressPath + File.separator + "compress.png";
  196. File image = new File(compressPath);
  197. if (image.exists()) {
  198. image.delete();
  199. }
  200. Intent intent = new Intent(
  201. Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  202. startActivityForResult(intent, resultCode);
  203. }
  204. /**
  205. * 内部类
  206. */
  207. class MyWebChromeClient extends WebChromeClient {
  208. //openFileChooser(隐藏方法)仅适用android5.0以下的环境,android5.0及以上使用onShowFileChooser
  209. // For Android 3.0+
  210. public void openFileChooser(ValueCallback<Uri> uploadMsg,
  211. String acceptType) {
  212. if (mUploadMessage != null)
  213. return;
  214. mUploadMessage = uploadMsg;
  215. selectImage(RESULT_CODE_PICK_FROM_ALBUM_BELLOW_LOLLILOP);
  216. }
  217. // For Android < 3.0
  218. public void openFileChooser(ValueCallback<Uri> uploadMsg) {
  219. openFileChooser(uploadMsg, "");
  220. }
  221. // For Android > 4.1.1
  222. public void openFileChooser(ValueCallback<Uri> uploadMsg,
  223. String acceptType, String capture) {
  224. openFileChooser(uploadMsg, acceptType);
  225. }
  226. // For Android 5.0+
  227. public boolean onShowFileChooser(WebView webView,
  228. ValueCallback<Uri[]> filePathCallback,
  229. FileChooserParams fileChooserParams) {
  230. mUploadCallbackAboveL = filePathCallback;
  231. selectImage(RESULT_CODE_PICK_FROM_ALBUM_ABOVE_LOLLILOP);
  232. return true;
  233. }
  234. @Override
  235. public void onProgressChanged(WebView view, int newProgress) {
  236. super.onProgressChanged(view, newProgress);
  237. }
  238. }
  239. }
  240. package com.lwd.webviewupimg;
  241. import java.io.BufferedOutputStream;
  242. import java.io.ByteArrayOutputStream;
  243. import java.io.File;
  244. import java.io.FileOutputStream;
  245. import java.io.IOException;
  246. import android.graphics.Bitmap;
  247. import android.graphics.Bitmap.CompressFormat;
  248. import android.graphics.Bitmap.Config;
  249. import android.graphics.BitmapFactory;
  250. import android.graphics.Matrix;
  251. import android.media.ExifInterface;
  252. import android.text.TextUtils;
  253. import android.util.Log;
  254. public class FileUtils {
  255. /**
  256. * 把图片压缩到200K
  257. *
  258. * @param oldpath
  259. * 压缩前的图片路径
  260. * @param newPath
  261. * 压缩后的图片路径
  262. * @return
  263. */
  264. public static File compressFile(String oldpath, String newPath) {
  265. Bitmap compressBitmap = FileUtils.decodeFile(oldpath);
  266. Bitmap newBitmap = ratingImage(oldpath, compressBitmap);
  267. ByteArrayOutputStream os = new ByteArrayOutputStream();
  268. newBitmap.compress(CompressFormat.PNG, 100, os);
  269. byte[] bytes = os.toByteArray();
  270. File file = null ;
  271. try {
  272. file = FileUtils.getFileFromBytes(bytes, newPath);
  273. } catch (Exception e) {
  274. e.printStackTrace();
  275. }finally{
  276. if(newBitmap != null ){
  277. if(!newBitmap.isRecycled()){
  278. newBitmap.recycle();
  279. }
  280. newBitmap = null;
  281. }
  282. if(compressBitmap != null ){
  283. if(!compressBitmap.isRecycled()){
  284. compressBitmap.recycle();
  285. }
  286. compressBitmap = null;
  287. }
  288. }
  289. return file;
  290. }
  291. private static Bitmap ratingImage(String filePath,Bitmap bitmap){
  292. int degree = readPictureDegree(filePath);
  293. return rotaingImageView(degree, bitmap);
  294. }
  295. /**
  296. * 旋转图片
  297. * @param angle
  298. * @param bitmap
  299. * @return Bitmap
  300. */
  301. public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
  302. //旋转图片 动作
  303. Matrix matrix = new Matrix();;
  304. matrix.postRotate(angle);
  305. System.out.println("angle2=" + angle);
  306. // 创建新的图片
  307. Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
  308. bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  309. return resizedBitmap;
  310. }
  311. /**
  312. * 读取图片属性:旋转的角度
  313. * @param path 图片绝对路径
  314. * @return degree旋转的角度
  315. */
  316. public static int readPictureDegree(String path) {
  317. int degree = 0;
  318. try {
  319. ExifInterface exifInterface = new ExifInterface(path);
  320. int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
  321. switch (orientation) {
  322. case ExifInterface.ORIENTATION_ROTATE_90:
  323. degree = 90;
  324. break;
  325. case ExifInterface.ORIENTATION_ROTATE_180:
  326. degree = 180;
  327. break;
  328. case ExifInterface.ORIENTATION_ROTATE_270:
  329. degree = 270;
  330. break;
  331. }
  332. } catch (IOException e) {
  333. e.printStackTrace();
  334. }
  335. return degree;
  336. }
  337. /**
  338. * 把字节数组保存为一个文件
  339. *
  340. * @param b
  341. * @param outputFile
  342. * @return
  343. */
  344. public static File getFileFromBytes(byte[] b, String outputFile) {
  345. File ret = null;
  346. BufferedOutputStream stream = null;
  347. try {
  348. ret = new File(outputFile);
  349. FileOutputStream fstream = new FileOutputStream(ret);
  350. stream = new BufferedOutputStream(fstream);
  351. stream.write(b);
  352. } catch (Exception e) {
  353. // log.error("helper:get file from byte process error!");
  354. e.printStackTrace();
  355. } finally {
  356. if (stream != null) {
  357. try {
  358. stream.close();
  359. } catch (IOException e) {
  360. // log.error("helper:get file from byte process error!");
  361. e.printStackTrace();
  362. }
  363. }
  364. }
  365. return ret;
  366. }
  367. /**
  368. * 图片压缩
  369. *
  370. * @param fPath
  371. * @return
  372. */
  373. public static Bitmap decodeFile(String fPath) {
  374. BitmapFactory.Options opts = new BitmapFactory.Options();
  375. opts.inJustDecodeBounds = true;
  376. opts.inDither = false; // Disable Dithering mode
  377. opts.inPurgeable = true; // Tell to gc that whether it needs free
  378. opts.inInputShareable = true; // Which kind of reference will be used to
  379. BitmapFactory.decodeFile(fPath, opts);
  380. final int REQUIRED_SIZE = 200;
  381. int scale = 1;
  382. if (opts.outHeight > REQUIRED_SIZE || opts.outWidth > REQUIRED_SIZE) {
  383. final int heightRatio = Math.round((float) opts.outHeight
  384. / (float) REQUIRED_SIZE);
  385. final int widthRatio = Math.round((float) opts.outWidth
  386. / (float) REQUIRED_SIZE);
  387. scale = heightRatio < widthRatio ? heightRatio : widthRatio;//
  388. }
  389. Log.i("scale", "scal ="+ scale);
  390. opts.inJustDecodeBounds = false;
  391. opts.inSampleSize = scale;
  392. Bitmap bm = BitmapFactory.decodeFile(fPath, opts).copy(Config.ARGB_8888, false);
  393. return bm;
  394. }
  395. /**
  396. * 创建目录
  397. * @param path
  398. */
  399. public static void setMkdir(String path)
  400. {
  401. File file = new File(path);
  402. if(!file.exists())
  403. {
  404. file.mkdirs();
  405. Log.e("file", "目录不存在 创建目录 ");
  406. }else{
  407. Log.e("file", "目录存在");
  408. }
  409. }
  410. /**
  411. * 获取目录名称
  412. * @param url
  413. * @return FileName
  414. */
  415. public static String getFileName(String url)
  416. {
  417. int lastIndexStart = url.lastIndexOf("/");
  418. if(lastIndexStart!=-1)
  419. {
  420. return url.substring(lastIndexStart+1, url.length());
  421. }else{
  422. return null;
  423. }
  424. }
  425. /**
  426. * 删除该目录下的文件
  427. *
  428. * @param path
  429. */
  430. public static void delFile(String path) {
  431. if (!TextUtils.isEmpty(path)) {
  432. File file = new File(path);
  433. if (file.exists()) {
  434. file.delete();
  435. }
  436. }
  437. }
  438. }

上面介绍了webView的上传,下面来介绍一下WebView的下载功能,
WebView 控制调用相应的WEB页面进行展示。当碰到页面有下载链接的时候,点击上去是一点反应都没有的。原来是因为WebView默认没有开启文件下载的功能,如 果要实现文件下载的功能,需要设置WebView的DownloadListener,通过实现自己的DownloadListener来实现文件的下 载。具体操作如下: 

1、设置WebView的DownloadListener: 
    webView.setDownloadListener(new MyWebViewDownLoadListener()); 

2、实现MyWebViewDownLoadListener这个类,具体可以如下这样:  
	
  1. private class MyWebViewDownLoadListener implements DownloadListener{
  2. @Override
  3. public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
  4. long contentLength) {
  5. Log.i("tag", "url="+url);
  6. Log.i("tag", "userAgent="+userAgent);
  7. Log.i("tag", "contentDisposition="+contentDisposition);
  8. Log.i("tag", "mimetype="+mimetype);
  9. Log.i("tag", "contentLength="+contentLength);
  10. Uri uri = Uri.parse(url);
  11. Intent intent = new Intent(Intent.ACTION_VIEW, uri);
  12. startActivity(intent);
  13. }
  14. }

这只是调用系统中已经内置的浏览器进行下载,还没有WebView本身进行的文件下载,不过,这也基本上满足我们的应用场景了。 

我在项目中的运用 
项目要求这样: 
1,需要使用WebView加载一个网页; 
2,网页中有文件下载的链接,点击后需要下载文件到SDcard; 
3,然后自动打开文件; 
下面是具体解决办法 
第一步,对WebView进行一系列设置。 
	
  1. WebView webview=(WebView)layout.findViewById(R.id.webview);
  2. webview.getSettings().setJavaScriptEnabled(true);
  3. webview.setWebChromeClient(new MyWebChromeClient());
  4. webview.requestFocus();
  5. // webview.loadUrl("file:///android_asset/risktest.html");
  6. webview.loadUrl(jcrs_sub.get(position).addr);
  7. // 设置web视图客户端
  8. webview.setWebViewClient(new MyWebViewClient());
  9. webview.setDownloadListener(new MyWebViewDownLoadListener());
  10. //内部类
  11. public class MyWebViewClient extends WebViewClient {
  12. // 如果页面中链接,如果希望点击链接继续在当前browser中响应,
  13. // 而不是新开Android的系统browser中响应该链接,必须覆盖 webview的WebViewClient对象。
  14. public boolean shouldOverviewUrlLoading(WebView view, String url) {
  15. L.i("shouldOverviewUrlLoading");
  16. view.loadUrl(url);
  17. return true;
  18. }
  19. public void onPageStarted(WebView view, String url, Bitmap favicon) {
  20. L.i("onPageStarted");
  21. showProgress();
  22. }
  23. public void onPageFinished(WebView view, String url) {
  24. L.i("onPageFinished");
  25. closeProgress();
  26. }
  27. public void onReceivedError(WebView view, int errorCode,
  28. String description, String failingUrl) {
  29. L.i("onReceivedError");
  30. closeProgress();
  31. }
  32. }
  33. // 如果不做任何处理,浏览网页,点击系统“Back”键,整个Browser会调用finish()而结束自身,
  34. // 如果希望浏览的网 页回退而不是推出浏览器,需要在当前Activity中处理并消费掉该Back事件。
  35. public boolean onKeyDown(int keyCode, KeyEvent event) {
  36. // if((keyCode==KeyEvent.KEYCODE_BACK)&&webview.canGoBack()){
  37. // webview.goBack();
  38. // return true;
  39. // }
  40. return false;
  41. }

	
  1. //内部类
  2. private class MyWebViewDownLoadListener implements DownloadListener {
  3. @Override
  4. public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
  5. long contentLength) {
  6. if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
  7. Toast t=Toast.makeText(mContext, "需要SD卡。", Toast.LENGTH_LONG);
  8. t.setGravity(Gravity.CENTER, 0, 0);
  9. t.show();
  10. return;
  11. }
  12. DownloaderTask task=new DownloaderTask();
  13. task.execute(url);
  14. }
  15. }
  16. //内部类
  17. private class DownloaderTask extends AsyncTask<String, Void, String> {
  18. public DownloaderTask() {
  19. }
  20. @Override
  21. protected String doInBackground(String... params) {
  22. // TODO Auto-generated method stub
  23. String url=params[0];
  24. // Log.i("tag", "url="+url);
  25. String fileName=url.substring(url.lastIndexOf("/")+1);
  26. fileName=URLDecoder.decode(fileName);
  27. Log.i("tag", "fileName="+fileName);
  28. File directory=Environment.getExternalStorageDirectory();
  29. File file=new File(directory,fileName);
  30. if(file.exists()){
  31. Log.i("tag", "The file has already exists.");
  32. return fileName;
  33. }
  34. try {
  35. HttpClient client = new DefaultHttpClient();
  36. // client.getParams().setIntParameter("http.socket.timeout",3000);//设置超时
  37. HttpGet get = new HttpGet(url);
  38. HttpResponse response = client.execute(get);
  39. if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
  40. HttpEntity entity = response.getEntity();
  41. InputStream input = entity.getContent();
  42. writeToSDCard(fileName,input);
  43. input.close();
  44. // entity.consumeContent();
  45. return fileName;
  46. }else{
  47. return null;
  48. }
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. return null;
  52. }
  53. }
  54. @Override
  55. protected void onCancelled() {
  56. // TODO Auto-generated method stub
  57. super.onCancelled();
  58. }
  59. @Override
  60. protected void onPostExecute(String result) {
  61. // TODO Auto-generated method stub
  62. super.onPostExecute(result);
  63. closeProgressDialog();
  64. if(result==null){
  65. Toast t=Toast.makeText(mContext, "连接错误!请稍后再试!", Toast.LENGTH_LONG);
  66. t.setGravity(Gravity.CENTER, 0, 0);
  67. t.show();
  68. return;
  69. }
  70. Toast t=Toast.makeText(mContext, "已保存到SD卡。", Toast.LENGTH_LONG);
  71. t.setGravity(Gravity.CENTER, 0, 0);
  72. t.show();
  73. File directory=Environment.getExternalStorageDirectory();
  74. File file=new File(directory,result);
  75. Log.i("tag", "Path="+file.getAbsolutePath());
  76. Intent intent = getFileIntent(file);
  77. startActivity(intent);
  78. }
  79. @Override
  80. protected void onPreExecute() {
  81. // TODO Auto-generated method stub
  82. super.onPreExecute();
  83. showProgressDialog();
  84. }
  85. @Override
  86. protected void onProgressUpdate(Void... values) {
  87. // TODO Auto-generated method stub
  88. super.onProgressUpdate(values);
  89. }
  90. }


经过上面的操作就完成了webView的上传和下载功能了。本人亲自测试过了,是有效果的,
宁夏银川舜新艺软件开发
ShunXinyi Soft develop
主要经营
软件开发,网站制作,网页设计,移动应用(安卓、苹果),微信,微网站,
FLASH动画,电子商务,计算机软硬件及网络设备等。
电话:18695132945 QQ:23923027
舜新艺软件开发 宁ICP备16001093号-1 宁公网安备 64010602000809号