在我的应用程序中,我使用webview导航到某个站点,使用javascript自动填写Web表单,然后提交以获取CSV导出文件的链接。 链接如下所示:XYZ.com/TEST/index/getexport?id=130。
我想下载此URL指向的文件,然后在完成时将其读入本地数据库,但我无法下载链接文件。
如果我只是尝试在webview中打开URL,我会从网页上收到错误,告诉我没有这样的文件。
如果我使用下载管理器自行下载,源代码将作为html文件下载,而不是关联的.csv文件。
我可以使用ACTION_VIEW意图打开网址,浏览器(chrome)会下载正确的文件,但这样我就没有通知下载何时完成。
有关如何下载.CSV文件的任何想法吗?
答案 0 :(得分:0)
要从webview下载文件,请使用以下命令:
mWebView.setDownloadListener(new DownloadListener(){
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
希望这有帮助。
答案 1 :(得分:0)
您可以使用AsyncTask手动从网址下载文件。
这里是背景部分:
@Override
protected String doInBackground(Void... params) {
String filename = "inputAFileName";
HttpURLConnection c;
try {
URL url = new URL("http://someurl/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file = new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
return e.getMessage();
}
if (file.exists()) {
return "File downloaded!";
} else {
Log.e(TAG, "file not found");
}
} else {
Log.e(TAG, "unable to create folder");
}
}
也许重构它以便返回文件是有意义的。然后在下载完成后立即将文件作为onPostExecute中的参数。